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/vendor/github.com/google/gnostic-models/openapiv3/document.go
vendor/github.com/google/gnostic-models/openapiv3/document.go
// Copyright 2020 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package openapi_v3 import ( "gopkg.in/yaml.v3" "github.com/google/gnostic-models/compiler" ) // ParseDocument reads an OpenAPI v3 description from a YAML/JSON representation. func ParseDocument(b []byte) (*Document, error) { info, err := compiler.ReadInfoFromBytes("", b) if err != nil { return nil, err } root := info.Content[0] return NewDocument(root, compiler.NewContextWithExtensions("$root", root, nil, nil)) } // YAMLValue produces a serialized YAML representation of the document. func (d *Document) YAMLValue(comment string) ([]byte, error) { rawInfo := d.ToRawInfo() rawInfo = &yaml.Node{ Kind: yaml.DocumentNode, Content: []*yaml.Node{rawInfo}, HeadComment: comment, } return yaml.Marshal(rawInfo) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/gnostic-models/openapiv3/OpenAPIv3.go
vendor/github.com/google/gnostic-models/openapiv3/OpenAPIv3.go
// Copyright 2020 Google LLC. All Rights Reserved. // // 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. // THIS FILE IS AUTOMATICALLY GENERATED. package openapi_v3 import ( "fmt" "regexp" "strings" "gopkg.in/yaml.v3" "github.com/google/gnostic-models/compiler" ) // Version returns the package name (and OpenAPI version). func Version() string { return "openapi_v3" } // NewAdditionalPropertiesItem creates an object of type AdditionalPropertiesItem if possible, returning an error if not. func NewAdditionalPropertiesItem(in *yaml.Node, context *compiler.Context) (*AdditionalPropertiesItem, error) { errors := make([]error, 0) x := &AdditionalPropertiesItem{} matched := false // SchemaOrReference schema_or_reference = 1; { m, ok := compiler.UnpackMap(in) if ok { // errors might be ok here, they mean we just don't have the right subtype t, matchingError := NewSchemaOrReference(m, compiler.NewContext("schemaOrReference", m, context)) if matchingError == nil { x.Oneof = &AdditionalPropertiesItem_SchemaOrReference{SchemaOrReference: t} matched = true } else { errors = append(errors, matchingError) } } } // bool boolean = 2; boolValue, ok := compiler.BoolForScalarNode(in) if ok { x.Oneof = &AdditionalPropertiesItem_Boolean{Boolean: boolValue} matched = true } if matched { // since the oneof matched one of its possibilities, discard any matching errors errors = make([]error, 0) } else { message := fmt.Sprintf("contains an invalid AdditionalPropertiesItem") err := compiler.NewError(context, message) errors = []error{err} } return x, compiler.NewErrorGroupOrNil(errors) } // NewAny creates an object of type Any if possible, returning an error if not. func NewAny(in *yaml.Node, context *compiler.Context) (*Any, error) { errors := make([]error, 0) x := &Any{} bytes := compiler.Marshal(in) x.Yaml = string(bytes) return x, compiler.NewErrorGroupOrNil(errors) } // NewAnyOrExpression creates an object of type AnyOrExpression if possible, returning an error if not. func NewAnyOrExpression(in *yaml.Node, context *compiler.Context) (*AnyOrExpression, error) { errors := make([]error, 0) x := &AnyOrExpression{} matched := false // Any any = 1; { m, ok := compiler.UnpackMap(in) if ok { // errors might be ok here, they mean we just don't have the right subtype t, matchingError := NewAny(m, compiler.NewContext("any", m, context)) if matchingError == nil { x.Oneof = &AnyOrExpression_Any{Any: t} matched = true } else { errors = append(errors, matchingError) } } } // Expression expression = 2; { m, ok := compiler.UnpackMap(in) if ok { // errors might be ok here, they mean we just don't have the right subtype t, matchingError := NewExpression(m, compiler.NewContext("expression", m, context)) if matchingError == nil { x.Oneof = &AnyOrExpression_Expression{Expression: t} matched = true } else { errors = append(errors, matchingError) } } } if matched { // since the oneof matched one of its possibilities, discard any matching errors errors = make([]error, 0) } else { message := fmt.Sprintf("contains an invalid AnyOrExpression") err := compiler.NewError(context, message) errors = []error{err} } return x, compiler.NewErrorGroupOrNil(errors) } // NewCallback creates an object of type Callback if possible, returning an error if not. func NewCallback(in *yaml.Node, context *compiler.Context) (*Callback, error) { errors := make([]error, 0) x := &Callback{} m, ok := compiler.UnpackMap(in) if !ok { message := fmt.Sprintf("has unexpected value: %+v (%T)", in, in) errors = append(errors, compiler.NewError(context, message)) } else { allowedKeys := []string{} allowedPatterns := []*regexp.Regexp{pattern0, pattern1} invalidKeys := compiler.InvalidKeysInMap(m, allowedKeys, allowedPatterns) if len(invalidKeys) > 0 { message := fmt.Sprintf("has invalid %s: %+v", compiler.PluralProperties(len(invalidKeys)), strings.Join(invalidKeys, ", ")) errors = append(errors, compiler.NewError(context, message)) } // repeated NamedPathItem path = 1; // MAP: PathItem ^ x.Path = make([]*NamedPathItem, 0) for i := 0; i < len(m.Content); i += 2 { k, ok := compiler.StringForScalarNode(m.Content[i]) if ok { v := m.Content[i+1] if true { pair := &NamedPathItem{} pair.Name = k var err error pair.Value, err = NewPathItem(v, compiler.NewContext(k, v, context)) if err != nil { errors = append(errors, err) } x.Path = append(x.Path, pair) } } } // repeated NamedAny specification_extension = 2; // MAP: Any ^x- x.SpecificationExtension = make([]*NamedAny, 0) for i := 0; i < len(m.Content); i += 2 { k, ok := compiler.StringForScalarNode(m.Content[i]) if ok { v := m.Content[i+1] if strings.HasPrefix(k, "x-") { pair := &NamedAny{} pair.Name = k result := &Any{} handled, resultFromExt, err := compiler.CallExtension(context, v, k) if handled { if err != nil { errors = append(errors, err) } else { bytes := compiler.Marshal(v) result.Yaml = string(bytes) result.Value = resultFromExt pair.Value = result } } else { pair.Value, err = NewAny(v, compiler.NewContext(k, v, context)) if err != nil { errors = append(errors, err) } } x.SpecificationExtension = append(x.SpecificationExtension, pair) } } } } return x, compiler.NewErrorGroupOrNil(errors) } // NewCallbackOrReference creates an object of type CallbackOrReference if possible, returning an error if not. func NewCallbackOrReference(in *yaml.Node, context *compiler.Context) (*CallbackOrReference, error) { errors := make([]error, 0) x := &CallbackOrReference{} matched := false // Callback callback = 1; { m, ok := compiler.UnpackMap(in) if ok { // errors might be ok here, they mean we just don't have the right subtype t, matchingError := NewCallback(m, compiler.NewContext("callback", m, context)) if matchingError == nil { x.Oneof = &CallbackOrReference_Callback{Callback: t} matched = true } else { errors = append(errors, matchingError) } } } // Reference reference = 2; { m, ok := compiler.UnpackMap(in) if ok { // errors might be ok here, they mean we just don't have the right subtype t, matchingError := NewReference(m, compiler.NewContext("reference", m, context)) if matchingError == nil { x.Oneof = &CallbackOrReference_Reference{Reference: t} matched = true } else { errors = append(errors, matchingError) } } } if matched { // since the oneof matched one of its possibilities, discard any matching errors errors = make([]error, 0) } else { message := fmt.Sprintf("contains an invalid CallbackOrReference") err := compiler.NewError(context, message) errors = []error{err} } return x, compiler.NewErrorGroupOrNil(errors) } // NewCallbacksOrReferences creates an object of type CallbacksOrReferences if possible, returning an error if not. func NewCallbacksOrReferences(in *yaml.Node, context *compiler.Context) (*CallbacksOrReferences, error) { errors := make([]error, 0) x := &CallbacksOrReferences{} m, ok := compiler.UnpackMap(in) if !ok { message := fmt.Sprintf("has unexpected value: %+v (%T)", in, in) errors = append(errors, compiler.NewError(context, message)) } else { // repeated NamedCallbackOrReference additional_properties = 1; // MAP: CallbackOrReference x.AdditionalProperties = make([]*NamedCallbackOrReference, 0) for i := 0; i < len(m.Content); i += 2 { k, ok := compiler.StringForScalarNode(m.Content[i]) if ok { v := m.Content[i+1] pair := &NamedCallbackOrReference{} pair.Name = k var err error pair.Value, err = NewCallbackOrReference(v, compiler.NewContext(k, v, context)) if err != nil { errors = append(errors, err) } x.AdditionalProperties = append(x.AdditionalProperties, pair) } } } return x, compiler.NewErrorGroupOrNil(errors) } // NewComponents creates an object of type Components if possible, returning an error if not. func NewComponents(in *yaml.Node, context *compiler.Context) (*Components, error) { errors := make([]error, 0) x := &Components{} m, ok := compiler.UnpackMap(in) if !ok { message := fmt.Sprintf("has unexpected value: %+v (%T)", in, in) errors = append(errors, compiler.NewError(context, message)) } else { allowedKeys := []string{"callbacks", "examples", "headers", "links", "parameters", "requestBodies", "responses", "schemas", "securitySchemes"} allowedPatterns := []*regexp.Regexp{pattern1} invalidKeys := compiler.InvalidKeysInMap(m, allowedKeys, allowedPatterns) if len(invalidKeys) > 0 { message := fmt.Sprintf("has invalid %s: %+v", compiler.PluralProperties(len(invalidKeys)), strings.Join(invalidKeys, ", ")) errors = append(errors, compiler.NewError(context, message)) } // SchemasOrReferences schemas = 1; v1 := compiler.MapValueForKey(m, "schemas") if v1 != nil { var err error x.Schemas, err = NewSchemasOrReferences(v1, compiler.NewContext("schemas", v1, context)) if err != nil { errors = append(errors, err) } } // ResponsesOrReferences responses = 2; v2 := compiler.MapValueForKey(m, "responses") if v2 != nil { var err error x.Responses, err = NewResponsesOrReferences(v2, compiler.NewContext("responses", v2, context)) if err != nil { errors = append(errors, err) } } // ParametersOrReferences parameters = 3; v3 := compiler.MapValueForKey(m, "parameters") if v3 != nil { var err error x.Parameters, err = NewParametersOrReferences(v3, compiler.NewContext("parameters", v3, context)) if err != nil { errors = append(errors, err) } } // ExamplesOrReferences examples = 4; v4 := compiler.MapValueForKey(m, "examples") if v4 != nil { var err error x.Examples, err = NewExamplesOrReferences(v4, compiler.NewContext("examples", v4, context)) if err != nil { errors = append(errors, err) } } // RequestBodiesOrReferences request_bodies = 5; v5 := compiler.MapValueForKey(m, "requestBodies") if v5 != nil { var err error x.RequestBodies, err = NewRequestBodiesOrReferences(v5, compiler.NewContext("requestBodies", v5, context)) if err != nil { errors = append(errors, err) } } // HeadersOrReferences headers = 6; v6 := compiler.MapValueForKey(m, "headers") if v6 != nil { var err error x.Headers, err = NewHeadersOrReferences(v6, compiler.NewContext("headers", v6, context)) if err != nil { errors = append(errors, err) } } // SecuritySchemesOrReferences security_schemes = 7; v7 := compiler.MapValueForKey(m, "securitySchemes") if v7 != nil { var err error x.SecuritySchemes, err = NewSecuritySchemesOrReferences(v7, compiler.NewContext("securitySchemes", v7, context)) if err != nil { errors = append(errors, err) } } // LinksOrReferences links = 8; v8 := compiler.MapValueForKey(m, "links") if v8 != nil { var err error x.Links, err = NewLinksOrReferences(v8, compiler.NewContext("links", v8, context)) if err != nil { errors = append(errors, err) } } // CallbacksOrReferences callbacks = 9; v9 := compiler.MapValueForKey(m, "callbacks") if v9 != nil { var err error x.Callbacks, err = NewCallbacksOrReferences(v9, compiler.NewContext("callbacks", v9, context)) if err != nil { errors = append(errors, err) } } // repeated NamedAny specification_extension = 10; // MAP: Any ^x- x.SpecificationExtension = make([]*NamedAny, 0) for i := 0; i < len(m.Content); i += 2 { k, ok := compiler.StringForScalarNode(m.Content[i]) if ok { v := m.Content[i+1] if strings.HasPrefix(k, "x-") { pair := &NamedAny{} pair.Name = k result := &Any{} handled, resultFromExt, err := compiler.CallExtension(context, v, k) if handled { if err != nil { errors = append(errors, err) } else { bytes := compiler.Marshal(v) result.Yaml = string(bytes) result.Value = resultFromExt pair.Value = result } } else { pair.Value, err = NewAny(v, compiler.NewContext(k, v, context)) if err != nil { errors = append(errors, err) } } x.SpecificationExtension = append(x.SpecificationExtension, pair) } } } } return x, compiler.NewErrorGroupOrNil(errors) } // NewContact creates an object of type Contact if possible, returning an error if not. func NewContact(in *yaml.Node, context *compiler.Context) (*Contact, error) { errors := make([]error, 0) x := &Contact{} m, ok := compiler.UnpackMap(in) if !ok { message := fmt.Sprintf("has unexpected value: %+v (%T)", in, in) errors = append(errors, compiler.NewError(context, message)) } else { allowedKeys := []string{"email", "name", "url"} allowedPatterns := []*regexp.Regexp{pattern1} invalidKeys := compiler.InvalidKeysInMap(m, allowedKeys, allowedPatterns) if len(invalidKeys) > 0 { message := fmt.Sprintf("has invalid %s: %+v", compiler.PluralProperties(len(invalidKeys)), strings.Join(invalidKeys, ", ")) errors = append(errors, compiler.NewError(context, message)) } // string name = 1; v1 := compiler.MapValueForKey(m, "name") if v1 != nil { x.Name, ok = compiler.StringForScalarNode(v1) if !ok { message := fmt.Sprintf("has unexpected value for name: %s", compiler.Display(v1)) errors = append(errors, compiler.NewError(context, message)) } } // string url = 2; v2 := compiler.MapValueForKey(m, "url") if v2 != nil { x.Url, ok = compiler.StringForScalarNode(v2) if !ok { message := fmt.Sprintf("has unexpected value for url: %s", compiler.Display(v2)) errors = append(errors, compiler.NewError(context, message)) } } // string email = 3; v3 := compiler.MapValueForKey(m, "email") if v3 != nil { x.Email, ok = compiler.StringForScalarNode(v3) if !ok { message := fmt.Sprintf("has unexpected value for email: %s", compiler.Display(v3)) errors = append(errors, compiler.NewError(context, message)) } } // repeated NamedAny specification_extension = 4; // MAP: Any ^x- x.SpecificationExtension = make([]*NamedAny, 0) for i := 0; i < len(m.Content); i += 2 { k, ok := compiler.StringForScalarNode(m.Content[i]) if ok { v := m.Content[i+1] if strings.HasPrefix(k, "x-") { pair := &NamedAny{} pair.Name = k result := &Any{} handled, resultFromExt, err := compiler.CallExtension(context, v, k) if handled { if err != nil { errors = append(errors, err) } else { bytes := compiler.Marshal(v) result.Yaml = string(bytes) result.Value = resultFromExt pair.Value = result } } else { pair.Value, err = NewAny(v, compiler.NewContext(k, v, context)) if err != nil { errors = append(errors, err) } } x.SpecificationExtension = append(x.SpecificationExtension, pair) } } } } return x, compiler.NewErrorGroupOrNil(errors) } // NewDefaultType creates an object of type DefaultType if possible, returning an error if not. func NewDefaultType(in *yaml.Node, context *compiler.Context) (*DefaultType, error) { errors := make([]error, 0) x := &DefaultType{} matched := false switch in.Tag { case "!!bool": var v bool v, matched = compiler.BoolForScalarNode(in) x.Oneof = &DefaultType_Boolean{Boolean: v} case "!!str": var v string v, matched = compiler.StringForScalarNode(in) x.Oneof = &DefaultType_String_{String_: v} case "!!float": var v float64 v, matched = compiler.FloatForScalarNode(in) x.Oneof = &DefaultType_Number{Number: v} case "!!int": var v int64 v, matched = compiler.IntForScalarNode(in) x.Oneof = &DefaultType_Number{Number: float64(v)} } if matched { // since the oneof matched one of its possibilities, discard any matching errors errors = make([]error, 0) } return x, compiler.NewErrorGroupOrNil(errors) } // NewDiscriminator creates an object of type Discriminator if possible, returning an error if not. func NewDiscriminator(in *yaml.Node, context *compiler.Context) (*Discriminator, error) { errors := make([]error, 0) x := &Discriminator{} m, ok := compiler.UnpackMap(in) if !ok { message := fmt.Sprintf("has unexpected value: %+v (%T)", in, in) errors = append(errors, compiler.NewError(context, message)) } else { requiredKeys := []string{"propertyName"} missingKeys := compiler.MissingKeysInMap(m, requiredKeys) if len(missingKeys) > 0 { message := fmt.Sprintf("is missing required %s: %+v", compiler.PluralProperties(len(missingKeys)), strings.Join(missingKeys, ", ")) errors = append(errors, compiler.NewError(context, message)) } allowedKeys := []string{"mapping", "propertyName"} allowedPatterns := []*regexp.Regexp{pattern1} invalidKeys := compiler.InvalidKeysInMap(m, allowedKeys, allowedPatterns) if len(invalidKeys) > 0 { message := fmt.Sprintf("has invalid %s: %+v", compiler.PluralProperties(len(invalidKeys)), strings.Join(invalidKeys, ", ")) errors = append(errors, compiler.NewError(context, message)) } // string property_name = 1; v1 := compiler.MapValueForKey(m, "propertyName") if v1 != nil { x.PropertyName, ok = compiler.StringForScalarNode(v1) if !ok { message := fmt.Sprintf("has unexpected value for propertyName: %s", compiler.Display(v1)) errors = append(errors, compiler.NewError(context, message)) } } // Strings mapping = 2; v2 := compiler.MapValueForKey(m, "mapping") if v2 != nil { var err error x.Mapping, err = NewStrings(v2, compiler.NewContext("mapping", v2, context)) if err != nil { errors = append(errors, err) } } // repeated NamedAny specification_extension = 3; // MAP: Any ^x- x.SpecificationExtension = make([]*NamedAny, 0) for i := 0; i < len(m.Content); i += 2 { k, ok := compiler.StringForScalarNode(m.Content[i]) if ok { v := m.Content[i+1] if strings.HasPrefix(k, "x-") { pair := &NamedAny{} pair.Name = k result := &Any{} handled, resultFromExt, err := compiler.CallExtension(context, v, k) if handled { if err != nil { errors = append(errors, err) } else { bytes := compiler.Marshal(v) result.Yaml = string(bytes) result.Value = resultFromExt pair.Value = result } } else { pair.Value, err = NewAny(v, compiler.NewContext(k, v, context)) if err != nil { errors = append(errors, err) } } x.SpecificationExtension = append(x.SpecificationExtension, pair) } } } } return x, compiler.NewErrorGroupOrNil(errors) } // NewDocument creates an object of type Document if possible, returning an error if not. func NewDocument(in *yaml.Node, context *compiler.Context) (*Document, error) { errors := make([]error, 0) x := &Document{} m, ok := compiler.UnpackMap(in) if !ok { message := fmt.Sprintf("has unexpected value: %+v (%T)", in, in) errors = append(errors, compiler.NewError(context, message)) } else { requiredKeys := []string{"info", "openapi", "paths"} missingKeys := compiler.MissingKeysInMap(m, requiredKeys) if len(missingKeys) > 0 { message := fmt.Sprintf("is missing required %s: %+v", compiler.PluralProperties(len(missingKeys)), strings.Join(missingKeys, ", ")) errors = append(errors, compiler.NewError(context, message)) } allowedKeys := []string{"components", "externalDocs", "info", "openapi", "paths", "security", "servers", "tags"} allowedPatterns := []*regexp.Regexp{pattern1} invalidKeys := compiler.InvalidKeysInMap(m, allowedKeys, allowedPatterns) if len(invalidKeys) > 0 { message := fmt.Sprintf("has invalid %s: %+v", compiler.PluralProperties(len(invalidKeys)), strings.Join(invalidKeys, ", ")) errors = append(errors, compiler.NewError(context, message)) } // string openapi = 1; v1 := compiler.MapValueForKey(m, "openapi") if v1 != nil { x.Openapi, ok = compiler.StringForScalarNode(v1) if !ok { message := fmt.Sprintf("has unexpected value for openapi: %s", compiler.Display(v1)) errors = append(errors, compiler.NewError(context, message)) } } // Info info = 2; v2 := compiler.MapValueForKey(m, "info") if v2 != nil { var err error x.Info, err = NewInfo(v2, compiler.NewContext("info", v2, context)) if err != nil { errors = append(errors, err) } } // repeated Server servers = 3; v3 := compiler.MapValueForKey(m, "servers") if v3 != nil { // repeated Server x.Servers = make([]*Server, 0) a, ok := compiler.SequenceNodeForNode(v3) if ok { for _, item := range a.Content { y, err := NewServer(item, compiler.NewContext("servers", item, context)) if err != nil { errors = append(errors, err) } x.Servers = append(x.Servers, y) } } } // Paths paths = 4; v4 := compiler.MapValueForKey(m, "paths") if v4 != nil { var err error x.Paths, err = NewPaths(v4, compiler.NewContext("paths", v4, context)) if err != nil { errors = append(errors, err) } } // Components components = 5; v5 := compiler.MapValueForKey(m, "components") if v5 != nil { var err error x.Components, err = NewComponents(v5, compiler.NewContext("components", v5, context)) if err != nil { errors = append(errors, err) } } // repeated SecurityRequirement security = 6; v6 := compiler.MapValueForKey(m, "security") if v6 != nil { // repeated SecurityRequirement x.Security = make([]*SecurityRequirement, 0) a, ok := compiler.SequenceNodeForNode(v6) if ok { for _, item := range a.Content { y, err := NewSecurityRequirement(item, compiler.NewContext("security", item, context)) if err != nil { errors = append(errors, err) } x.Security = append(x.Security, y) } } } // repeated Tag tags = 7; v7 := compiler.MapValueForKey(m, "tags") if v7 != nil { // repeated Tag x.Tags = make([]*Tag, 0) a, ok := compiler.SequenceNodeForNode(v7) if ok { for _, item := range a.Content { y, err := NewTag(item, compiler.NewContext("tags", item, context)) if err != nil { errors = append(errors, err) } x.Tags = append(x.Tags, y) } } } // ExternalDocs external_docs = 8; v8 := compiler.MapValueForKey(m, "externalDocs") if v8 != nil { var err error x.ExternalDocs, err = NewExternalDocs(v8, compiler.NewContext("externalDocs", v8, context)) if err != nil { errors = append(errors, err) } } // repeated NamedAny specification_extension = 9; // MAP: Any ^x- x.SpecificationExtension = make([]*NamedAny, 0) for i := 0; i < len(m.Content); i += 2 { k, ok := compiler.StringForScalarNode(m.Content[i]) if ok { v := m.Content[i+1] if strings.HasPrefix(k, "x-") { pair := &NamedAny{} pair.Name = k result := &Any{} handled, resultFromExt, err := compiler.CallExtension(context, v, k) if handled { if err != nil { errors = append(errors, err) } else { bytes := compiler.Marshal(v) result.Yaml = string(bytes) result.Value = resultFromExt pair.Value = result } } else { pair.Value, err = NewAny(v, compiler.NewContext(k, v, context)) if err != nil { errors = append(errors, err) } } x.SpecificationExtension = append(x.SpecificationExtension, pair) } } } } return x, compiler.NewErrorGroupOrNil(errors) } // NewEncoding creates an object of type Encoding if possible, returning an error if not. func NewEncoding(in *yaml.Node, context *compiler.Context) (*Encoding, error) { errors := make([]error, 0) x := &Encoding{} m, ok := compiler.UnpackMap(in) if !ok { message := fmt.Sprintf("has unexpected value: %+v (%T)", in, in) errors = append(errors, compiler.NewError(context, message)) } else { allowedKeys := []string{"allowReserved", "contentType", "explode", "headers", "style"} allowedPatterns := []*regexp.Regexp{pattern1} invalidKeys := compiler.InvalidKeysInMap(m, allowedKeys, allowedPatterns) if len(invalidKeys) > 0 { message := fmt.Sprintf("has invalid %s: %+v", compiler.PluralProperties(len(invalidKeys)), strings.Join(invalidKeys, ", ")) errors = append(errors, compiler.NewError(context, message)) } // string content_type = 1; v1 := compiler.MapValueForKey(m, "contentType") if v1 != nil { x.ContentType, ok = compiler.StringForScalarNode(v1) if !ok { message := fmt.Sprintf("has unexpected value for contentType: %s", compiler.Display(v1)) errors = append(errors, compiler.NewError(context, message)) } } // HeadersOrReferences headers = 2; v2 := compiler.MapValueForKey(m, "headers") if v2 != nil { var err error x.Headers, err = NewHeadersOrReferences(v2, compiler.NewContext("headers", v2, context)) if err != nil { errors = append(errors, err) } } // string style = 3; v3 := compiler.MapValueForKey(m, "style") if v3 != nil { x.Style, ok = compiler.StringForScalarNode(v3) if !ok { message := fmt.Sprintf("has unexpected value for style: %s", compiler.Display(v3)) errors = append(errors, compiler.NewError(context, message)) } } // bool explode = 4; v4 := compiler.MapValueForKey(m, "explode") if v4 != nil { x.Explode, ok = compiler.BoolForScalarNode(v4) if !ok { message := fmt.Sprintf("has unexpected value for explode: %s", compiler.Display(v4)) errors = append(errors, compiler.NewError(context, message)) } } // bool allow_reserved = 5; v5 := compiler.MapValueForKey(m, "allowReserved") if v5 != nil { x.AllowReserved, ok = compiler.BoolForScalarNode(v5) if !ok { message := fmt.Sprintf("has unexpected value for allowReserved: %s", compiler.Display(v5)) errors = append(errors, compiler.NewError(context, message)) } } // repeated NamedAny specification_extension = 6; // MAP: Any ^x- x.SpecificationExtension = make([]*NamedAny, 0) for i := 0; i < len(m.Content); i += 2 { k, ok := compiler.StringForScalarNode(m.Content[i]) if ok { v := m.Content[i+1] if strings.HasPrefix(k, "x-") { pair := &NamedAny{} pair.Name = k result := &Any{} handled, resultFromExt, err := compiler.CallExtension(context, v, k) if handled { if err != nil { errors = append(errors, err) } else { bytes := compiler.Marshal(v) result.Yaml = string(bytes) result.Value = resultFromExt pair.Value = result } } else { pair.Value, err = NewAny(v, compiler.NewContext(k, v, context)) if err != nil { errors = append(errors, err) } } x.SpecificationExtension = append(x.SpecificationExtension, pair) } } } } return x, compiler.NewErrorGroupOrNil(errors) } // NewEncodings creates an object of type Encodings if possible, returning an error if not. func NewEncodings(in *yaml.Node, context *compiler.Context) (*Encodings, error) { errors := make([]error, 0) x := &Encodings{} m, ok := compiler.UnpackMap(in) if !ok { message := fmt.Sprintf("has unexpected value: %+v (%T)", in, in) errors = append(errors, compiler.NewError(context, message)) } else { // repeated NamedEncoding additional_properties = 1; // MAP: Encoding x.AdditionalProperties = make([]*NamedEncoding, 0) for i := 0; i < len(m.Content); i += 2 { k, ok := compiler.StringForScalarNode(m.Content[i]) if ok { v := m.Content[i+1] pair := &NamedEncoding{} pair.Name = k var err error pair.Value, err = NewEncoding(v, compiler.NewContext(k, v, context)) if err != nil { errors = append(errors, err) } x.AdditionalProperties = append(x.AdditionalProperties, pair) } } } return x, compiler.NewErrorGroupOrNil(errors) } // NewExample creates an object of type Example if possible, returning an error if not. func NewExample(in *yaml.Node, context *compiler.Context) (*Example, error) { errors := make([]error, 0) x := &Example{} m, ok := compiler.UnpackMap(in) if !ok { message := fmt.Sprintf("has unexpected value: %+v (%T)", in, in) errors = append(errors, compiler.NewError(context, message)) } else { allowedKeys := []string{"description", "externalValue", "summary", "value"} allowedPatterns := []*regexp.Regexp{pattern1} invalidKeys := compiler.InvalidKeysInMap(m, allowedKeys, allowedPatterns) if len(invalidKeys) > 0 { message := fmt.Sprintf("has invalid %s: %+v", compiler.PluralProperties(len(invalidKeys)), strings.Join(invalidKeys, ", ")) errors = append(errors, compiler.NewError(context, message)) } // string summary = 1; v1 := compiler.MapValueForKey(m, "summary") if v1 != nil { x.Summary, ok = compiler.StringForScalarNode(v1) if !ok { message := fmt.Sprintf("has unexpected value for summary: %s", compiler.Display(v1)) errors = append(errors, compiler.NewError(context, message)) } } // string description = 2; v2 := compiler.MapValueForKey(m, "description") if v2 != nil { x.Description, ok = compiler.StringForScalarNode(v2) if !ok { message := fmt.Sprintf("has unexpected value for description: %s", compiler.Display(v2)) errors = append(errors, compiler.NewError(context, message)) } } // Any value = 3; v3 := compiler.MapValueForKey(m, "value") if v3 != nil { var err error x.Value, err = NewAny(v3, compiler.NewContext("value", v3, context)) if err != nil { errors = append(errors, err) } } // string external_value = 4; v4 := compiler.MapValueForKey(m, "externalValue") if v4 != nil { x.ExternalValue, ok = compiler.StringForScalarNode(v4) if !ok { message := fmt.Sprintf("has unexpected value for externalValue: %s", compiler.Display(v4)) errors = append(errors, compiler.NewError(context, message)) } } // repeated NamedAny specification_extension = 5; // MAP: Any ^x- x.SpecificationExtension = make([]*NamedAny, 0) for i := 0; i < len(m.Content); i += 2 { k, ok := compiler.StringForScalarNode(m.Content[i]) if ok { v := m.Content[i+1] if strings.HasPrefix(k, "x-") { pair := &NamedAny{} pair.Name = k result := &Any{} handled, resultFromExt, err := compiler.CallExtension(context, v, k) if handled { if err != nil { errors = append(errors, err) } else { bytes := compiler.Marshal(v) result.Yaml = string(bytes) result.Value = resultFromExt pair.Value = result } } else { pair.Value, err = NewAny(v, compiler.NewContext(k, v, context)) if err != nil { errors = append(errors, err) } } x.SpecificationExtension = append(x.SpecificationExtension, pair) } } } } return x, compiler.NewErrorGroupOrNil(errors) } // NewExampleOrReference creates an object of type ExampleOrReference if possible, returning an error if not. func NewExampleOrReference(in *yaml.Node, context *compiler.Context) (*ExampleOrReference, error) { errors := make([]error, 0) x := &ExampleOrReference{} matched := false // Example example = 1; { m, ok := compiler.UnpackMap(in) if ok { // errors might be ok here, they mean we just don't have the right subtype t, matchingError := NewExample(m, compiler.NewContext("example", m, context)) if matchingError == nil { x.Oneof = &ExampleOrReference_Example{Example: t} matched = true } else { errors = append(errors, matchingError) } } } // Reference reference = 2; { m, ok := compiler.UnpackMap(in) if ok { // errors might be ok here, they mean we just don't have the right subtype t, matchingError := NewReference(m, compiler.NewContext("reference", m, context)) if matchingError == nil { x.Oneof = &ExampleOrReference_Reference{Reference: t} matched = true } else { errors = append(errors, matchingError) } } } if matched { // since the oneof matched one of its possibilities, discard any matching errors errors = make([]error, 0) } else {
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/gnostic-models/openapiv3/OpenAPIv3.pb.go
vendor/github.com/google/gnostic-models/openapiv3/OpenAPIv3.pb.go
// Copyright 2020 Google LLC. All Rights Reserved. // // 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. // THIS FILE IS AUTOMATICALLY GENERATED. // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.27.1 // protoc v3.19.3 // source: openapiv3/OpenAPIv3.proto package openapi_v3 import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" anypb "google.golang.org/protobuf/types/known/anypb" reflect "reflect" sync "sync" ) 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) ) type AdditionalPropertiesItem struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Types that are assignable to Oneof: // *AdditionalPropertiesItem_SchemaOrReference // *AdditionalPropertiesItem_Boolean Oneof isAdditionalPropertiesItem_Oneof `protobuf_oneof:"oneof"` } func (x *AdditionalPropertiesItem) Reset() { *x = AdditionalPropertiesItem{} if protoimpl.UnsafeEnabled { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AdditionalPropertiesItem) String() string { return protoimpl.X.MessageStringOf(x) } func (*AdditionalPropertiesItem) ProtoMessage() {} func (x *AdditionalPropertiesItem) ProtoReflect() protoreflect.Message { mi := &file_openapiv3_OpenAPIv3_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 AdditionalPropertiesItem.ProtoReflect.Descriptor instead. func (*AdditionalPropertiesItem) Descriptor() ([]byte, []int) { return file_openapiv3_OpenAPIv3_proto_rawDescGZIP(), []int{0} } func (m *AdditionalPropertiesItem) GetOneof() isAdditionalPropertiesItem_Oneof { if m != nil { return m.Oneof } return nil } func (x *AdditionalPropertiesItem) GetSchemaOrReference() *SchemaOrReference { if x, ok := x.GetOneof().(*AdditionalPropertiesItem_SchemaOrReference); ok { return x.SchemaOrReference } return nil } func (x *AdditionalPropertiesItem) GetBoolean() bool { if x, ok := x.GetOneof().(*AdditionalPropertiesItem_Boolean); ok { return x.Boolean } return false } type isAdditionalPropertiesItem_Oneof interface { isAdditionalPropertiesItem_Oneof() } type AdditionalPropertiesItem_SchemaOrReference struct { SchemaOrReference *SchemaOrReference `protobuf:"bytes,1,opt,name=schema_or_reference,json=schemaOrReference,proto3,oneof"` } type AdditionalPropertiesItem_Boolean struct { Boolean bool `protobuf:"varint,2,opt,name=boolean,proto3,oneof"` } func (*AdditionalPropertiesItem_SchemaOrReference) isAdditionalPropertiesItem_Oneof() {} func (*AdditionalPropertiesItem_Boolean) isAdditionalPropertiesItem_Oneof() {} type Any struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Value *anypb.Any `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"` Yaml string `protobuf:"bytes,2,opt,name=yaml,proto3" json:"yaml,omitempty"` } func (x *Any) Reset() { *x = Any{} if protoimpl.UnsafeEnabled { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[1] 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_openapiv3_OpenAPIv3_proto_msgTypes[1] 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 Any.ProtoReflect.Descriptor instead. func (*Any) Descriptor() ([]byte, []int) { return file_openapiv3_OpenAPIv3_proto_rawDescGZIP(), []int{1} } func (x *Any) GetValue() *anypb.Any { if x != nil { return x.Value } return nil } func (x *Any) GetYaml() string { if x != nil { return x.Yaml } return "" } type AnyOrExpression struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Types that are assignable to Oneof: // *AnyOrExpression_Any // *AnyOrExpression_Expression Oneof isAnyOrExpression_Oneof `protobuf_oneof:"oneof"` } func (x *AnyOrExpression) Reset() { *x = AnyOrExpression{} if protoimpl.UnsafeEnabled { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *AnyOrExpression) String() string { return protoimpl.X.MessageStringOf(x) } func (*AnyOrExpression) ProtoMessage() {} func (x *AnyOrExpression) ProtoReflect() protoreflect.Message { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[2] 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 AnyOrExpression.ProtoReflect.Descriptor instead. func (*AnyOrExpression) Descriptor() ([]byte, []int) { return file_openapiv3_OpenAPIv3_proto_rawDescGZIP(), []int{2} } func (m *AnyOrExpression) GetOneof() isAnyOrExpression_Oneof { if m != nil { return m.Oneof } return nil } func (x *AnyOrExpression) GetAny() *Any { if x, ok := x.GetOneof().(*AnyOrExpression_Any); ok { return x.Any } return nil } func (x *AnyOrExpression) GetExpression() *Expression { if x, ok := x.GetOneof().(*AnyOrExpression_Expression); ok { return x.Expression } return nil } type isAnyOrExpression_Oneof interface { isAnyOrExpression_Oneof() } type AnyOrExpression_Any struct { Any *Any `protobuf:"bytes,1,opt,name=any,proto3,oneof"` } type AnyOrExpression_Expression struct { Expression *Expression `protobuf:"bytes,2,opt,name=expression,proto3,oneof"` } func (*AnyOrExpression_Any) isAnyOrExpression_Oneof() {} func (*AnyOrExpression_Expression) isAnyOrExpression_Oneof() {} // A map of possible out-of band callbacks related to the parent operation. Each value in the map is a Path Item Object that describes a set of requests that may be initiated by the API provider and the expected responses. The key value used to identify the callback object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation. type Callback struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Path []*NamedPathItem `protobuf:"bytes,1,rep,name=path,proto3" json:"path,omitempty"` SpecificationExtension []*NamedAny `protobuf:"bytes,2,rep,name=specification_extension,json=specificationExtension,proto3" json:"specification_extension,omitempty"` } func (x *Callback) Reset() { *x = Callback{} if protoimpl.UnsafeEnabled { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Callback) String() string { return protoimpl.X.MessageStringOf(x) } func (*Callback) ProtoMessage() {} func (x *Callback) ProtoReflect() protoreflect.Message { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[3] 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 Callback.ProtoReflect.Descriptor instead. func (*Callback) Descriptor() ([]byte, []int) { return file_openapiv3_OpenAPIv3_proto_rawDescGZIP(), []int{3} } func (x *Callback) GetPath() []*NamedPathItem { if x != nil { return x.Path } return nil } func (x *Callback) GetSpecificationExtension() []*NamedAny { if x != nil { return x.SpecificationExtension } return nil } type CallbackOrReference struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Types that are assignable to Oneof: // *CallbackOrReference_Callback // *CallbackOrReference_Reference Oneof isCallbackOrReference_Oneof `protobuf_oneof:"oneof"` } func (x *CallbackOrReference) Reset() { *x = CallbackOrReference{} if protoimpl.UnsafeEnabled { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *CallbackOrReference) String() string { return protoimpl.X.MessageStringOf(x) } func (*CallbackOrReference) ProtoMessage() {} func (x *CallbackOrReference) ProtoReflect() protoreflect.Message { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[4] 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 CallbackOrReference.ProtoReflect.Descriptor instead. func (*CallbackOrReference) Descriptor() ([]byte, []int) { return file_openapiv3_OpenAPIv3_proto_rawDescGZIP(), []int{4} } func (m *CallbackOrReference) GetOneof() isCallbackOrReference_Oneof { if m != nil { return m.Oneof } return nil } func (x *CallbackOrReference) GetCallback() *Callback { if x, ok := x.GetOneof().(*CallbackOrReference_Callback); ok { return x.Callback } return nil } func (x *CallbackOrReference) GetReference() *Reference { if x, ok := x.GetOneof().(*CallbackOrReference_Reference); ok { return x.Reference } return nil } type isCallbackOrReference_Oneof interface { isCallbackOrReference_Oneof() } type CallbackOrReference_Callback struct { Callback *Callback `protobuf:"bytes,1,opt,name=callback,proto3,oneof"` } type CallbackOrReference_Reference struct { Reference *Reference `protobuf:"bytes,2,opt,name=reference,proto3,oneof"` } func (*CallbackOrReference_Callback) isCallbackOrReference_Oneof() {} func (*CallbackOrReference_Reference) isCallbackOrReference_Oneof() {} type CallbacksOrReferences struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields AdditionalProperties []*NamedCallbackOrReference `protobuf:"bytes,1,rep,name=additional_properties,json=additionalProperties,proto3" json:"additional_properties,omitempty"` } func (x *CallbacksOrReferences) Reset() { *x = CallbacksOrReferences{} if protoimpl.UnsafeEnabled { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *CallbacksOrReferences) String() string { return protoimpl.X.MessageStringOf(x) } func (*CallbacksOrReferences) ProtoMessage() {} func (x *CallbacksOrReferences) ProtoReflect() protoreflect.Message { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[5] 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 CallbacksOrReferences.ProtoReflect.Descriptor instead. func (*CallbacksOrReferences) Descriptor() ([]byte, []int) { return file_openapiv3_OpenAPIv3_proto_rawDescGZIP(), []int{5} } func (x *CallbacksOrReferences) GetAdditionalProperties() []*NamedCallbackOrReference { if x != nil { return x.AdditionalProperties } return nil } // Holds a set of reusable objects for different aspects of the OAS. All objects defined within the components object will have no effect on the API unless they are explicitly referenced from properties outside the components object. type Components struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Schemas *SchemasOrReferences `protobuf:"bytes,1,opt,name=schemas,proto3" json:"schemas,omitempty"` Responses *ResponsesOrReferences `protobuf:"bytes,2,opt,name=responses,proto3" json:"responses,omitempty"` Parameters *ParametersOrReferences `protobuf:"bytes,3,opt,name=parameters,proto3" json:"parameters,omitempty"` Examples *ExamplesOrReferences `protobuf:"bytes,4,opt,name=examples,proto3" json:"examples,omitempty"` RequestBodies *RequestBodiesOrReferences `protobuf:"bytes,5,opt,name=request_bodies,json=requestBodies,proto3" json:"request_bodies,omitempty"` Headers *HeadersOrReferences `protobuf:"bytes,6,opt,name=headers,proto3" json:"headers,omitempty"` SecuritySchemes *SecuritySchemesOrReferences `protobuf:"bytes,7,opt,name=security_schemes,json=securitySchemes,proto3" json:"security_schemes,omitempty"` Links *LinksOrReferences `protobuf:"bytes,8,opt,name=links,proto3" json:"links,omitempty"` Callbacks *CallbacksOrReferences `protobuf:"bytes,9,opt,name=callbacks,proto3" json:"callbacks,omitempty"` SpecificationExtension []*NamedAny `protobuf:"bytes,10,rep,name=specification_extension,json=specificationExtension,proto3" json:"specification_extension,omitempty"` } func (x *Components) Reset() { *x = Components{} if protoimpl.UnsafeEnabled { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Components) String() string { return protoimpl.X.MessageStringOf(x) } func (*Components) ProtoMessage() {} func (x *Components) ProtoReflect() protoreflect.Message { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[6] 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 Components.ProtoReflect.Descriptor instead. func (*Components) Descriptor() ([]byte, []int) { return file_openapiv3_OpenAPIv3_proto_rawDescGZIP(), []int{6} } func (x *Components) GetSchemas() *SchemasOrReferences { if x != nil { return x.Schemas } return nil } func (x *Components) GetResponses() *ResponsesOrReferences { if x != nil { return x.Responses } return nil } func (x *Components) GetParameters() *ParametersOrReferences { if x != nil { return x.Parameters } return nil } func (x *Components) GetExamples() *ExamplesOrReferences { if x != nil { return x.Examples } return nil } func (x *Components) GetRequestBodies() *RequestBodiesOrReferences { if x != nil { return x.RequestBodies } return nil } func (x *Components) GetHeaders() *HeadersOrReferences { if x != nil { return x.Headers } return nil } func (x *Components) GetSecuritySchemes() *SecuritySchemesOrReferences { if x != nil { return x.SecuritySchemes } return nil } func (x *Components) GetLinks() *LinksOrReferences { if x != nil { return x.Links } return nil } func (x *Components) GetCallbacks() *CallbacksOrReferences { if x != nil { return x.Callbacks } return nil } func (x *Components) GetSpecificationExtension() []*NamedAny { if x != nil { return x.SpecificationExtension } return nil } // Contact information for the exposed API. type Contact struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` Url string `protobuf:"bytes,2,opt,name=url,proto3" json:"url,omitempty"` Email string `protobuf:"bytes,3,opt,name=email,proto3" json:"email,omitempty"` SpecificationExtension []*NamedAny `protobuf:"bytes,4,rep,name=specification_extension,json=specificationExtension,proto3" json:"specification_extension,omitempty"` } func (x *Contact) Reset() { *x = Contact{} if protoimpl.UnsafeEnabled { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Contact) String() string { return protoimpl.X.MessageStringOf(x) } func (*Contact) ProtoMessage() {} func (x *Contact) ProtoReflect() protoreflect.Message { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[7] 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 Contact.ProtoReflect.Descriptor instead. func (*Contact) Descriptor() ([]byte, []int) { return file_openapiv3_OpenAPIv3_proto_rawDescGZIP(), []int{7} } func (x *Contact) GetName() string { if x != nil { return x.Name } return "" } func (x *Contact) GetUrl() string { if x != nil { return x.Url } return "" } func (x *Contact) GetEmail() string { if x != nil { return x.Email } return "" } func (x *Contact) GetSpecificationExtension() []*NamedAny { if x != nil { return x.SpecificationExtension } return nil } type DefaultType struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Types that are assignable to Oneof: // *DefaultType_Number // *DefaultType_Boolean // *DefaultType_String_ Oneof isDefaultType_Oneof `protobuf_oneof:"oneof"` } func (x *DefaultType) Reset() { *x = DefaultType{} if protoimpl.UnsafeEnabled { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *DefaultType) String() string { return protoimpl.X.MessageStringOf(x) } func (*DefaultType) ProtoMessage() {} func (x *DefaultType) ProtoReflect() protoreflect.Message { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[8] 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 DefaultType.ProtoReflect.Descriptor instead. func (*DefaultType) Descriptor() ([]byte, []int) { return file_openapiv3_OpenAPIv3_proto_rawDescGZIP(), []int{8} } func (m *DefaultType) GetOneof() isDefaultType_Oneof { if m != nil { return m.Oneof } return nil } func (x *DefaultType) GetNumber() float64 { if x, ok := x.GetOneof().(*DefaultType_Number); ok { return x.Number } return 0 } func (x *DefaultType) GetBoolean() bool { if x, ok := x.GetOneof().(*DefaultType_Boolean); ok { return x.Boolean } return false } func (x *DefaultType) GetString_() string { if x, ok := x.GetOneof().(*DefaultType_String_); ok { return x.String_ } return "" } type isDefaultType_Oneof interface { isDefaultType_Oneof() } type DefaultType_Number struct { Number float64 `protobuf:"fixed64,1,opt,name=number,proto3,oneof"` } type DefaultType_Boolean struct { Boolean bool `protobuf:"varint,2,opt,name=boolean,proto3,oneof"` } type DefaultType_String_ struct { String_ string `protobuf:"bytes,3,opt,name=string,proto3,oneof"` } func (*DefaultType_Number) isDefaultType_Oneof() {} func (*DefaultType_Boolean) isDefaultType_Oneof() {} func (*DefaultType_String_) isDefaultType_Oneof() {} // When request bodies or response payloads may be one of a number of different schemas, a `discriminator` object can be used to aid in serialization, deserialization, and validation. The discriminator is a specific object in a schema which is used to inform the consumer of the specification of an alternative schema based on the value associated with it. When using the discriminator, _inline_ schemas will not be considered. type Discriminator struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields PropertyName string `protobuf:"bytes,1,opt,name=property_name,json=propertyName,proto3" json:"property_name,omitempty"` Mapping *Strings `protobuf:"bytes,2,opt,name=mapping,proto3" json:"mapping,omitempty"` SpecificationExtension []*NamedAny `protobuf:"bytes,3,rep,name=specification_extension,json=specificationExtension,proto3" json:"specification_extension,omitempty"` } func (x *Discriminator) Reset() { *x = Discriminator{} if protoimpl.UnsafeEnabled { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[9] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Discriminator) String() string { return protoimpl.X.MessageStringOf(x) } func (*Discriminator) ProtoMessage() {} func (x *Discriminator) ProtoReflect() protoreflect.Message { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[9] 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 Discriminator.ProtoReflect.Descriptor instead. func (*Discriminator) Descriptor() ([]byte, []int) { return file_openapiv3_OpenAPIv3_proto_rawDescGZIP(), []int{9} } func (x *Discriminator) GetPropertyName() string { if x != nil { return x.PropertyName } return "" } func (x *Discriminator) GetMapping() *Strings { if x != nil { return x.Mapping } return nil } func (x *Discriminator) GetSpecificationExtension() []*NamedAny { if x != nil { return x.SpecificationExtension } return nil } type Document struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Openapi string `protobuf:"bytes,1,opt,name=openapi,proto3" json:"openapi,omitempty"` Info *Info `protobuf:"bytes,2,opt,name=info,proto3" json:"info,omitempty"` Servers []*Server `protobuf:"bytes,3,rep,name=servers,proto3" json:"servers,omitempty"` Paths *Paths `protobuf:"bytes,4,opt,name=paths,proto3" json:"paths,omitempty"` Components *Components `protobuf:"bytes,5,opt,name=components,proto3" json:"components,omitempty"` Security []*SecurityRequirement `protobuf:"bytes,6,rep,name=security,proto3" json:"security,omitempty"` Tags []*Tag `protobuf:"bytes,7,rep,name=tags,proto3" json:"tags,omitempty"` ExternalDocs *ExternalDocs `protobuf:"bytes,8,opt,name=external_docs,json=externalDocs,proto3" json:"external_docs,omitempty"` SpecificationExtension []*NamedAny `protobuf:"bytes,9,rep,name=specification_extension,json=specificationExtension,proto3" json:"specification_extension,omitempty"` } func (x *Document) Reset() { *x = Document{} if protoimpl.UnsafeEnabled { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[10] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Document) String() string { return protoimpl.X.MessageStringOf(x) } func (*Document) ProtoMessage() {} func (x *Document) ProtoReflect() protoreflect.Message { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[10] 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 Document.ProtoReflect.Descriptor instead. func (*Document) Descriptor() ([]byte, []int) { return file_openapiv3_OpenAPIv3_proto_rawDescGZIP(), []int{10} } func (x *Document) GetOpenapi() string { if x != nil { return x.Openapi } return "" } func (x *Document) GetInfo() *Info { if x != nil { return x.Info } return nil } func (x *Document) GetServers() []*Server { if x != nil { return x.Servers } return nil } func (x *Document) GetPaths() *Paths { if x != nil { return x.Paths } return nil } func (x *Document) GetComponents() *Components { if x != nil { return x.Components } return nil } func (x *Document) GetSecurity() []*SecurityRequirement { if x != nil { return x.Security } return nil } func (x *Document) GetTags() []*Tag { if x != nil { return x.Tags } return nil } func (x *Document) GetExternalDocs() *ExternalDocs { if x != nil { return x.ExternalDocs } return nil } func (x *Document) GetSpecificationExtension() []*NamedAny { if x != nil { return x.SpecificationExtension } return nil } // A single encoding definition applied to a single schema property. type Encoding struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields ContentType string `protobuf:"bytes,1,opt,name=content_type,json=contentType,proto3" json:"content_type,omitempty"` Headers *HeadersOrReferences `protobuf:"bytes,2,opt,name=headers,proto3" json:"headers,omitempty"` Style string `protobuf:"bytes,3,opt,name=style,proto3" json:"style,omitempty"` Explode bool `protobuf:"varint,4,opt,name=explode,proto3" json:"explode,omitempty"` AllowReserved bool `protobuf:"varint,5,opt,name=allow_reserved,json=allowReserved,proto3" json:"allow_reserved,omitempty"` SpecificationExtension []*NamedAny `protobuf:"bytes,6,rep,name=specification_extension,json=specificationExtension,proto3" json:"specification_extension,omitempty"` } func (x *Encoding) Reset() { *x = Encoding{} if protoimpl.UnsafeEnabled { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[11] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Encoding) String() string { return protoimpl.X.MessageStringOf(x) } func (*Encoding) ProtoMessage() {} func (x *Encoding) ProtoReflect() protoreflect.Message { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[11] 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 Encoding.ProtoReflect.Descriptor instead. func (*Encoding) Descriptor() ([]byte, []int) { return file_openapiv3_OpenAPIv3_proto_rawDescGZIP(), []int{11} } func (x *Encoding) GetContentType() string { if x != nil { return x.ContentType } return "" } func (x *Encoding) GetHeaders() *HeadersOrReferences { if x != nil { return x.Headers } return nil } func (x *Encoding) GetStyle() string { if x != nil { return x.Style } return "" } func (x *Encoding) GetExplode() bool { if x != nil { return x.Explode } return false } func (x *Encoding) GetAllowReserved() bool { if x != nil { return x.AllowReserved } return false } func (x *Encoding) GetSpecificationExtension() []*NamedAny { if x != nil { return x.SpecificationExtension } return nil } type Encodings struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields AdditionalProperties []*NamedEncoding `protobuf:"bytes,1,rep,name=additional_properties,json=additionalProperties,proto3" json:"additional_properties,omitempty"` } func (x *Encodings) Reset() { *x = Encodings{} if protoimpl.UnsafeEnabled { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[12] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Encodings) String() string { return protoimpl.X.MessageStringOf(x) } func (*Encodings) ProtoMessage() {} func (x *Encodings) ProtoReflect() protoreflect.Message { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[12] 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 Encodings.ProtoReflect.Descriptor instead. func (*Encodings) Descriptor() ([]byte, []int) { return file_openapiv3_OpenAPIv3_proto_rawDescGZIP(), []int{12} } func (x *Encodings) GetAdditionalProperties() []*NamedEncoding { if x != nil { return x.AdditionalProperties } return nil } type Example struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Summary string `protobuf:"bytes,1,opt,name=summary,proto3" json:"summary,omitempty"` Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` Value *Any `protobuf:"bytes,3,opt,name=value,proto3" json:"value,omitempty"` ExternalValue string `protobuf:"bytes,4,opt,name=external_value,json=externalValue,proto3" json:"external_value,omitempty"` SpecificationExtension []*NamedAny `protobuf:"bytes,5,rep,name=specification_extension,json=specificationExtension,proto3" json:"specification_extension,omitempty"` } func (x *Example) Reset() { *x = Example{} if protoimpl.UnsafeEnabled { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[13] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Example) String() string { return protoimpl.X.MessageStringOf(x) } func (*Example) ProtoMessage() {} func (x *Example) ProtoReflect() protoreflect.Message { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[13] 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 Example.ProtoReflect.Descriptor instead. func (*Example) Descriptor() ([]byte, []int) { return file_openapiv3_OpenAPIv3_proto_rawDescGZIP(), []int{13} } func (x *Example) GetSummary() string { if x != nil { return x.Summary } return "" } func (x *Example) GetDescription() string { if x != nil { return x.Description } return "" } func (x *Example) GetValue() *Any { if x != nil { return x.Value } return nil } func (x *Example) GetExternalValue() string { if x != nil { return x.ExternalValue } return "" } func (x *Example) GetSpecificationExtension() []*NamedAny { if x != nil { return x.SpecificationExtension } return nil } type ExampleOrReference struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // Types that are assignable to Oneof: // *ExampleOrReference_Example // *ExampleOrReference_Reference Oneof isExampleOrReference_Oneof `protobuf_oneof:"oneof"` } func (x *ExampleOrReference) Reset() { *x = ExampleOrReference{} if protoimpl.UnsafeEnabled { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[14] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *ExampleOrReference) String() string { return protoimpl.X.MessageStringOf(x) } func (*ExampleOrReference) ProtoMessage() {} func (x *ExampleOrReference) ProtoReflect() protoreflect.Message { mi := &file_openapiv3_OpenAPIv3_proto_msgTypes[14] 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 ExampleOrReference.ProtoReflect.Descriptor instead. func (*ExampleOrReference) Descriptor() ([]byte, []int) { return file_openapiv3_OpenAPIv3_proto_rawDescGZIP(), []int{14} } func (m *ExampleOrReference) GetOneof() isExampleOrReference_Oneof { if m != nil { return m.Oneof } return nil } func (x *ExampleOrReference) GetExample() *Example { if x, ok := x.GetOneof().(*ExampleOrReference_Example); ok { return x.Example } return nil } func (x *ExampleOrReference) GetReference() *Reference { if x, ok := x.GetOneof().(*ExampleOrReference_Reference); ok { return x.Reference } return nil } type isExampleOrReference_Oneof interface { isExampleOrReference_Oneof() } type ExampleOrReference_Example struct {
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/gnostic-models/compiler/error.go
vendor/github.com/google/gnostic-models/compiler/error.go
// Copyright 2017 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package compiler import "fmt" // Error represents compiler errors and their location in the document. type Error struct { Context *Context Message string } // NewError creates an Error. func NewError(context *Context, message string) *Error { return &Error{Context: context, Message: message} } func (err *Error) locationDescription() string { if err.Context.Node != nil { return fmt.Sprintf("[%d,%d] %s", err.Context.Node.Line, err.Context.Node.Column, err.Context.Description()) } return err.Context.Description() } // Error returns the string value of an Error. func (err *Error) Error() string { if err.Context == nil { return err.Message } return err.locationDescription() + " " + err.Message } // ErrorGroup is a container for groups of Error values. type ErrorGroup struct { Errors []error } // NewErrorGroupOrNil returns a new ErrorGroup for a slice of errors or nil if the slice is empty. func NewErrorGroupOrNil(errors []error) error { if len(errors) == 0 { return nil } else if len(errors) == 1 { return errors[0] } else { return &ErrorGroup{Errors: errors} } } func (group *ErrorGroup) Error() string { result := "" for i, err := range group.Errors { if i > 0 { result += "\n" } result += err.Error() } return result }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/gnostic-models/compiler/reader.go
vendor/github.com/google/gnostic-models/compiler/reader.go
// Copyright 2017 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package compiler import ( "fmt" "io/ioutil" "log" "net/http" "net/url" "path/filepath" "strings" "sync" yaml "gopkg.in/yaml.v3" ) var verboseReader = false var fileCache map[string][]byte var infoCache map[string]*yaml.Node var fileCacheEnable = true var infoCacheEnable = true // These locks are used to synchronize accesses to the fileCache and infoCache // maps (above). They are global state and can throw thread-related errors // when modified from separate goroutines. The general strategy is to protect // all public functions in this file with mutex Lock() calls. As a result, to // avoid deadlock, these public functions should not call other public // functions, so some public functions have private equivalents. // In the future, we might consider replacing the maps with sync.Map and // eliminating these mutexes. var fileCacheMutex sync.Mutex var infoCacheMutex sync.Mutex func initializeFileCache() { if fileCache == nil { fileCache = make(map[string][]byte, 0) } } func initializeInfoCache() { if infoCache == nil { infoCache = make(map[string]*yaml.Node, 0) } } // EnableFileCache turns on file caching. func EnableFileCache() { fileCacheMutex.Lock() defer fileCacheMutex.Unlock() fileCacheEnable = true } // EnableInfoCache turns on parsed info caching. func EnableInfoCache() { infoCacheMutex.Lock() defer infoCacheMutex.Unlock() infoCacheEnable = true } // DisableFileCache turns off file caching. func DisableFileCache() { fileCacheMutex.Lock() defer fileCacheMutex.Unlock() fileCacheEnable = false } // DisableInfoCache turns off parsed info caching. func DisableInfoCache() { infoCacheMutex.Lock() defer infoCacheMutex.Unlock() infoCacheEnable = false } // RemoveFromFileCache removes an entry from the file cache. func RemoveFromFileCache(fileurl string) { fileCacheMutex.Lock() defer fileCacheMutex.Unlock() if !fileCacheEnable { return } initializeFileCache() delete(fileCache, fileurl) } // RemoveFromInfoCache removes an entry from the info cache. func RemoveFromInfoCache(filename string) { infoCacheMutex.Lock() defer infoCacheMutex.Unlock() if !infoCacheEnable { return } initializeInfoCache() delete(infoCache, filename) } // GetInfoCache returns the info cache map. func GetInfoCache() map[string]*yaml.Node { infoCacheMutex.Lock() defer infoCacheMutex.Unlock() if infoCache == nil { initializeInfoCache() } return infoCache } // ClearFileCache clears the file cache. func ClearFileCache() { fileCacheMutex.Lock() defer fileCacheMutex.Unlock() fileCache = make(map[string][]byte, 0) } // ClearInfoCache clears the info cache. func ClearInfoCache() { infoCacheMutex.Lock() defer infoCacheMutex.Unlock() infoCache = make(map[string]*yaml.Node) } // ClearCaches clears all caches. func ClearCaches() { ClearFileCache() ClearInfoCache() } // FetchFile gets a specified file from the local filesystem or a remote location. func FetchFile(fileurl string) ([]byte, error) { fileCacheMutex.Lock() defer fileCacheMutex.Unlock() return fetchFile(fileurl) } func fetchFile(fileurl string) ([]byte, error) { var bytes []byte initializeFileCache() if fileCacheEnable { bytes, ok := fileCache[fileurl] if ok { if verboseReader { log.Printf("Cache hit %s", fileurl) } return bytes, nil } if verboseReader { log.Printf("Fetching %s", fileurl) } } response, err := http.Get(fileurl) if err != nil { return nil, err } defer response.Body.Close() if response.StatusCode != 200 { return nil, fmt.Errorf("Error downloading %s: %s", fileurl, response.Status) } bytes, err = ioutil.ReadAll(response.Body) if fileCacheEnable && err == nil { fileCache[fileurl] = bytes } return bytes, err } // ReadBytesForFile reads the bytes of a file. func ReadBytesForFile(filename string) ([]byte, error) { fileCacheMutex.Lock() defer fileCacheMutex.Unlock() return readBytesForFile(filename) } func readBytesForFile(filename string) ([]byte, error) { // is the filename a url? fileurl, _ := url.Parse(filename) if fileurl.Scheme != "" { // yes, fetch it bytes, err := fetchFile(filename) if err != nil { return nil, err } return bytes, nil } // no, it's a local filename bytes, err := ioutil.ReadFile(filename) if err != nil { return nil, err } return bytes, nil } // ReadInfoFromBytes unmarshals a file as a *yaml.Node. func ReadInfoFromBytes(filename string, bytes []byte) (*yaml.Node, error) { infoCacheMutex.Lock() defer infoCacheMutex.Unlock() return readInfoFromBytes(filename, bytes) } func readInfoFromBytes(filename string, bytes []byte) (*yaml.Node, error) { initializeInfoCache() if infoCacheEnable { cachedInfo, ok := infoCache[filename] if ok { if verboseReader { log.Printf("Cache hit info for file %s", filename) } return cachedInfo, nil } if verboseReader { log.Printf("Reading info for file %s", filename) } } var info yaml.Node err := yaml.Unmarshal(bytes, &info) if err != nil { return nil, err } if infoCacheEnable && len(filename) > 0 { infoCache[filename] = &info } return &info, nil } // ReadInfoForRef reads a file and return the fragment needed to resolve a $ref. func ReadInfoForRef(basefile string, ref string) (*yaml.Node, error) { fileCacheMutex.Lock() defer fileCacheMutex.Unlock() infoCacheMutex.Lock() defer infoCacheMutex.Unlock() initializeInfoCache() if infoCacheEnable { info, ok := infoCache[ref] if ok { if verboseReader { log.Printf("Cache hit for ref %s#%s", basefile, ref) } return info, nil } if verboseReader { log.Printf("Reading info for ref %s#%s", basefile, ref) } } basedir, _ := filepath.Split(basefile) parts := strings.Split(ref, "#") var filename string if parts[0] != "" { filename = parts[0] if _, err := url.ParseRequestURI(parts[0]); err != nil { // It is not an URL, so the file is local filename = basedir + parts[0] } } else { filename = basefile } bytes, err := readBytesForFile(filename) if err != nil { return nil, err } info, err := readInfoFromBytes(filename, bytes) if info != nil && info.Kind == yaml.DocumentNode { info = info.Content[0] } if err != nil { log.Printf("File error: %v\n", err) } else { if info == nil { return nil, NewError(nil, fmt.Sprintf("could not resolve %s", ref)) } if len(parts) > 1 { path := strings.Split(parts[1], "/") for i, key := range path { if i > 0 { m := info if true { found := false for i := 0; i < len(m.Content); i += 2 { if m.Content[i].Value == key { info = m.Content[i+1] found = true } } if !found { infoCache[ref] = nil return nil, NewError(nil, fmt.Sprintf("could not resolve %s", ref)) } } } } } } if infoCacheEnable { infoCache[ref] = info } return info, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/gnostic-models/compiler/extensions.go
vendor/github.com/google/gnostic-models/compiler/extensions.go
// Copyright 2017 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package compiler import ( "bytes" "fmt" "os/exec" "strings" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/ptypes/any" yaml "gopkg.in/yaml.v3" extensions "github.com/google/gnostic-models/extensions" ) // ExtensionHandler describes a binary that is called by the compiler to handle specification extensions. type ExtensionHandler struct { Name string } // CallExtension calls a binary extension handler. func CallExtension(context *Context, in *yaml.Node, extensionName string) (handled bool, response *any.Any, err error) { if context == nil || context.ExtensionHandlers == nil { return false, nil, nil } handled = false for _, handler := range *(context.ExtensionHandlers) { response, err = handler.handle(in, extensionName) if response == nil { continue } else { handled = true break } } return handled, response, err } func (extensionHandlers *ExtensionHandler) handle(in *yaml.Node, extensionName string) (*any.Any, error) { if extensionHandlers.Name != "" { yamlData, _ := yaml.Marshal(in) request := &extensions.ExtensionHandlerRequest{ CompilerVersion: &extensions.Version{ Major: 0, Minor: 1, Patch: 0, }, Wrapper: &extensions.Wrapper{ Version: "unknown", // TODO: set this to the type/version of spec being parsed. Yaml: string(yamlData), ExtensionName: extensionName, }, } requestBytes, _ := proto.Marshal(request) cmd := exec.Command(extensionHandlers.Name) cmd.Stdin = bytes.NewReader(requestBytes) output, err := cmd.Output() if err != nil { return nil, err } response := &extensions.ExtensionHandlerResponse{} err = proto.Unmarshal(output, response) if err != nil || !response.Handled { return nil, err } if len(response.Errors) != 0 { return nil, fmt.Errorf("Errors when parsing: %+v for field %s by vendor extension handler %s. Details %+v", in, extensionName, extensionHandlers.Name, strings.Join(response.Errors, ",")) } return response.Value, nil } return nil, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/gnostic-models/compiler/context.go
vendor/github.com/google/gnostic-models/compiler/context.go
// Copyright 2017 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package compiler import ( yaml "gopkg.in/yaml.v3" ) // Context contains state of the compiler as it traverses a document. type Context struct { Parent *Context Name string Node *yaml.Node ExtensionHandlers *[]ExtensionHandler } // NewContextWithExtensions returns a new object representing the compiler state func NewContextWithExtensions(name string, node *yaml.Node, parent *Context, extensionHandlers *[]ExtensionHandler) *Context { return &Context{Name: name, Node: node, Parent: parent, ExtensionHandlers: extensionHandlers} } // NewContext returns a new object representing the compiler state func NewContext(name string, node *yaml.Node, parent *Context) *Context { if parent != nil { return &Context{Name: name, Node: node, Parent: parent, ExtensionHandlers: parent.ExtensionHandlers} } return &Context{Name: name, Parent: parent, ExtensionHandlers: nil} } // Description returns a text description of the compiler state func (context *Context) Description() string { name := context.Name if context.Parent != nil { name = context.Parent.Description() + "." + name } return name }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/gnostic-models/compiler/helpers.go
vendor/github.com/google/gnostic-models/compiler/helpers.go
// Copyright 2017 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package compiler import ( "fmt" "regexp" "sort" "strconv" "gopkg.in/yaml.v3" "github.com/google/gnostic-models/jsonschema" ) // compiler helper functions, usually called from generated code // UnpackMap gets a *yaml.Node if possible. func UnpackMap(in *yaml.Node) (*yaml.Node, bool) { if in == nil { return nil, false } return in, true } // SortedKeysForMap returns the sorted keys of a yamlv2.MapSlice. func SortedKeysForMap(m *yaml.Node) []string { keys := make([]string, 0) if m.Kind == yaml.MappingNode { for i := 0; i < len(m.Content); i += 2 { keys = append(keys, m.Content[i].Value) } } sort.Strings(keys) return keys } // MapHasKey returns true if a yamlv2.MapSlice contains a specified key. func MapHasKey(m *yaml.Node, key string) bool { if m == nil { return false } if m.Kind == yaml.MappingNode { for i := 0; i < len(m.Content); i += 2 { itemKey := m.Content[i].Value if key == itemKey { return true } } } return false } // MapValueForKey gets the value of a map value for a specified key. func MapValueForKey(m *yaml.Node, key string) *yaml.Node { if m == nil { return nil } if m.Kind == yaml.MappingNode { for i := 0; i < len(m.Content); i += 2 { itemKey := m.Content[i].Value if key == itemKey { return m.Content[i+1] } } } return nil } // ConvertInterfaceArrayToStringArray converts an array of interfaces to an array of strings, if possible. func ConvertInterfaceArrayToStringArray(interfaceArray []interface{}) []string { stringArray := make([]string, 0) for _, item := range interfaceArray { v, ok := item.(string) if ok { stringArray = append(stringArray, v) } } return stringArray } // SequenceNodeForNode returns a node if it is a SequenceNode. func SequenceNodeForNode(node *yaml.Node) (*yaml.Node, bool) { if node.Kind != yaml.SequenceNode { return nil, false } return node, true } // BoolForScalarNode returns the bool value of a node. func BoolForScalarNode(node *yaml.Node) (bool, bool) { if node == nil { return false, false } if node.Kind == yaml.DocumentNode { return BoolForScalarNode(node.Content[0]) } if node.Kind != yaml.ScalarNode { return false, false } if node.Tag != "!!bool" { return false, false } v, err := strconv.ParseBool(node.Value) if err != nil { return false, false } return v, true } // IntForScalarNode returns the integer value of a node. func IntForScalarNode(node *yaml.Node) (int64, bool) { if node == nil { return 0, false } if node.Kind == yaml.DocumentNode { return IntForScalarNode(node.Content[0]) } if node.Kind != yaml.ScalarNode { return 0, false } if node.Tag != "!!int" { return 0, false } v, err := strconv.ParseInt(node.Value, 10, 64) if err != nil { return 0, false } return v, true } // FloatForScalarNode returns the float value of a node. func FloatForScalarNode(node *yaml.Node) (float64, bool) { if node == nil { return 0.0, false } if node.Kind == yaml.DocumentNode { return FloatForScalarNode(node.Content[0]) } if node.Kind != yaml.ScalarNode { return 0.0, false } if (node.Tag != "!!int") && (node.Tag != "!!float") { return 0.0, false } v, err := strconv.ParseFloat(node.Value, 64) if err != nil { return 0.0, false } return v, true } // StringForScalarNode returns the string value of a node. func StringForScalarNode(node *yaml.Node) (string, bool) { if node == nil { return "", false } if node.Kind == yaml.DocumentNode { return StringForScalarNode(node.Content[0]) } switch node.Kind { case yaml.ScalarNode: switch node.Tag { case "!!int": return node.Value, true case "!!str": return node.Value, true case "!!timestamp": return node.Value, true case "!!null": return "", true default: return "", false } default: return "", false } } // StringArrayForSequenceNode converts a sequence node to an array of strings, if possible. func StringArrayForSequenceNode(node *yaml.Node) []string { stringArray := make([]string, 0) for _, item := range node.Content { v, ok := StringForScalarNode(item) if ok { stringArray = append(stringArray, v) } } return stringArray } // MissingKeysInMap identifies which keys from a list of required keys are not in a map. func MissingKeysInMap(m *yaml.Node, requiredKeys []string) []string { missingKeys := make([]string, 0) for _, k := range requiredKeys { if !MapHasKey(m, k) { missingKeys = append(missingKeys, k) } } return missingKeys } // InvalidKeysInMap returns keys in a map that don't match a list of allowed keys and patterns. func InvalidKeysInMap(m *yaml.Node, allowedKeys []string, allowedPatterns []*regexp.Regexp) []string { invalidKeys := make([]string, 0) if m == nil || m.Kind != yaml.MappingNode { return invalidKeys } for i := 0; i < len(m.Content); i += 2 { key := m.Content[i].Value found := false // does the key match an allowed key? for _, allowedKey := range allowedKeys { if key == allowedKey { found = true break } } if !found { // does the key match an allowed pattern? for _, allowedPattern := range allowedPatterns { if allowedPattern.MatchString(key) { found = true break } } if !found { invalidKeys = append(invalidKeys, key) } } } return invalidKeys } // NewNullNode creates a new Null node. func NewNullNode() *yaml.Node { node := &yaml.Node{ Kind: yaml.ScalarNode, Tag: "!!null", } return node } // NewMappingNode creates a new Mapping node. func NewMappingNode() *yaml.Node { return &yaml.Node{ Kind: yaml.MappingNode, Content: make([]*yaml.Node, 0), } } // NewSequenceNode creates a new Sequence node. func NewSequenceNode() *yaml.Node { node := &yaml.Node{ Kind: yaml.SequenceNode, Content: make([]*yaml.Node, 0), } return node } // NewScalarNodeForString creates a new node to hold a string. func NewScalarNodeForString(s string) *yaml.Node { return &yaml.Node{ Kind: yaml.ScalarNode, Tag: "!!str", Value: s, } } // NewSequenceNodeForStringArray creates a new node to hold an array of strings. func NewSequenceNodeForStringArray(strings []string) *yaml.Node { node := &yaml.Node{ Kind: yaml.SequenceNode, Content: make([]*yaml.Node, 0), } for _, s := range strings { node.Content = append(node.Content, NewScalarNodeForString(s)) } return node } // NewScalarNodeForBool creates a new node to hold a bool. func NewScalarNodeForBool(b bool) *yaml.Node { return &yaml.Node{ Kind: yaml.ScalarNode, Tag: "!!bool", Value: fmt.Sprintf("%t", b), } } // NewScalarNodeForFloat creates a new node to hold a float. func NewScalarNodeForFloat(f float64) *yaml.Node { return &yaml.Node{ Kind: yaml.ScalarNode, Tag: "!!float", Value: fmt.Sprintf("%g", f), } } // NewScalarNodeForInt creates a new node to hold an integer. func NewScalarNodeForInt(i int64) *yaml.Node { return &yaml.Node{ Kind: yaml.ScalarNode, Tag: "!!int", Value: fmt.Sprintf("%d", i), } } // PluralProperties returns the string "properties" pluralized. func PluralProperties(count int) string { if count == 1 { return "property" } return "properties" } // StringArrayContainsValue returns true if a string array contains a specified value. func StringArrayContainsValue(array []string, value string) bool { for _, item := range array { if item == value { return true } } return false } // StringArrayContainsValues returns true if a string array contains all of a list of specified values. func StringArrayContainsValues(array []string, values []string) bool { for _, value := range values { if !StringArrayContainsValue(array, value) { return false } } return true } // StringValue returns the string value of an item. func StringValue(item interface{}) (value string, ok bool) { value, ok = item.(string) if ok { return value, ok } intValue, ok := item.(int) if ok { return strconv.Itoa(intValue), true } return "", false } // Description returns a human-readable represention of an item. func Description(item interface{}) string { value, ok := item.(*yaml.Node) if ok { return jsonschema.Render(value) } return fmt.Sprintf("%+v", item) } // Display returns a description of a node for use in error messages. func Display(node *yaml.Node) string { switch node.Kind { case yaml.ScalarNode: switch node.Tag { case "!!str": return fmt.Sprintf("%s (string)", node.Value) } } return fmt.Sprintf("%+v (%T)", node, node) } // Marshal creates a yaml version of a structure in our preferred style func Marshal(in *yaml.Node) []byte { clearStyle(in) //bytes, _ := yaml.Marshal(&yaml.Node{Kind: yaml.DocumentNode, Content: []*yaml.Node{in}}) bytes, _ := yaml.Marshal(in) return bytes } func clearStyle(node *yaml.Node) { node.Style = 0 for _, c := range node.Content { clearStyle(c) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/gnostic-models/compiler/main.go
vendor/github.com/google/gnostic-models/compiler/main.go
// Copyright 2017 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package compiler provides support functions to generated compiler code. package compiler
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/gofuzz/fuzz.go
vendor/github.com/google/gofuzz/fuzz.go
/* Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package fuzz import ( "fmt" "math/rand" "reflect" "regexp" "time" "github.com/google/gofuzz/bytesource" "strings" ) // fuzzFuncMap is a map from a type to a fuzzFunc that handles that type. type fuzzFuncMap map[reflect.Type]reflect.Value // Fuzzer knows how to fill any object with random fields. type Fuzzer struct { fuzzFuncs fuzzFuncMap defaultFuzzFuncs fuzzFuncMap r *rand.Rand nilChance float64 minElements int maxElements int maxDepth int skipFieldPatterns []*regexp.Regexp } // New returns a new Fuzzer. Customize your Fuzzer further by calling Funcs, // RandSource, NilChance, or NumElements in any order. func New() *Fuzzer { return NewWithSeed(time.Now().UnixNano()) } func NewWithSeed(seed int64) *Fuzzer { f := &Fuzzer{ defaultFuzzFuncs: fuzzFuncMap{ reflect.TypeOf(&time.Time{}): reflect.ValueOf(fuzzTime), }, fuzzFuncs: fuzzFuncMap{}, r: rand.New(rand.NewSource(seed)), nilChance: .2, minElements: 1, maxElements: 10, maxDepth: 100, } return f } // NewFromGoFuzz is a helper function that enables using gofuzz (this // project) with go-fuzz (https://github.com/dvyukov/go-fuzz) for continuous // fuzzing. Essentially, it enables translating the fuzzing bytes from // go-fuzz to any Go object using this library. // // This implementation promises a constant translation from a given slice of // bytes to the fuzzed objects. This promise will remain over future // versions of Go and of this library. // // Note: the returned Fuzzer should not be shared between multiple goroutines, // as its deterministic output will no longer be available. // // Example: use go-fuzz to test the function `MyFunc(int)` in the package // `mypackage`. Add the file: "mypacakge_fuzz.go" with the content: // // // +build gofuzz // package mypacakge // import fuzz "github.com/google/gofuzz" // func Fuzz(data []byte) int { // var i int // fuzz.NewFromGoFuzz(data).Fuzz(&i) // MyFunc(i) // return 0 // } func NewFromGoFuzz(data []byte) *Fuzzer { return New().RandSource(bytesource.New(data)) } // Funcs adds each entry in fuzzFuncs as a custom fuzzing function. // // Each entry in fuzzFuncs must be a function taking two parameters. // The first parameter must be a pointer or map. It is the variable that // function will fill with random data. The second parameter must be a // fuzz.Continue, which will provide a source of randomness and a way // to automatically continue fuzzing smaller pieces of the first parameter. // // These functions are called sensibly, e.g., if you wanted custom string // fuzzing, the function `func(s *string, c fuzz.Continue)` would get // called and passed the address of strings. Maps and pointers will always // be made/new'd for you, ignoring the NilChange option. For slices, it // doesn't make much sense to pre-create them--Fuzzer doesn't know how // long you want your slice--so take a pointer to a slice, and make it // yourself. (If you don't want your map/pointer type pre-made, take a // pointer to it, and make it yourself.) See the examples for a range of // custom functions. func (f *Fuzzer) Funcs(fuzzFuncs ...interface{}) *Fuzzer { for i := range fuzzFuncs { v := reflect.ValueOf(fuzzFuncs[i]) if v.Kind() != reflect.Func { panic("Need only funcs!") } t := v.Type() if t.NumIn() != 2 || t.NumOut() != 0 { panic("Need 2 in and 0 out params!") } argT := t.In(0) switch argT.Kind() { case reflect.Ptr, reflect.Map: default: panic("fuzzFunc must take pointer or map type") } if t.In(1) != reflect.TypeOf(Continue{}) { panic("fuzzFunc's second parameter must be type fuzz.Continue") } f.fuzzFuncs[argT] = v } return f } // RandSource causes f to get values from the given source of randomness. // Use if you want deterministic fuzzing. func (f *Fuzzer) RandSource(s rand.Source) *Fuzzer { f.r = rand.New(s) return f } // NilChance sets the probability of creating a nil pointer, map, or slice to // 'p'. 'p' should be between 0 (no nils) and 1 (all nils), inclusive. func (f *Fuzzer) NilChance(p float64) *Fuzzer { if p < 0 || p > 1 { panic("p should be between 0 and 1, inclusive.") } f.nilChance = p return f } // NumElements sets the minimum and maximum number of elements that will be // added to a non-nil map or slice. func (f *Fuzzer) NumElements(atLeast, atMost int) *Fuzzer { if atLeast > atMost { panic("atLeast must be <= atMost") } if atLeast < 0 { panic("atLeast must be >= 0") } f.minElements = atLeast f.maxElements = atMost return f } func (f *Fuzzer) genElementCount() int { if f.minElements == f.maxElements { return f.minElements } return f.minElements + f.r.Intn(f.maxElements-f.minElements+1) } func (f *Fuzzer) genShouldFill() bool { return f.r.Float64() >= f.nilChance } // MaxDepth sets the maximum number of recursive fuzz calls that will be made // before stopping. This includes struct members, pointers, and map and slice // elements. func (f *Fuzzer) MaxDepth(d int) *Fuzzer { f.maxDepth = d return f } // Skip fields which match the supplied pattern. Call this multiple times if needed // This is useful to skip XXX_ fields generated by protobuf func (f *Fuzzer) SkipFieldsWithPattern(pattern *regexp.Regexp) *Fuzzer { f.skipFieldPatterns = append(f.skipFieldPatterns, pattern) return f } // Fuzz recursively fills all of obj's fields with something random. First // this tries to find a custom fuzz function (see Funcs). If there is no // custom function this tests whether the object implements fuzz.Interface and, // if so, calls Fuzz on it to fuzz itself. If that fails, this will see if // there is a default fuzz function provided by this package. If all of that // fails, this will generate random values for all primitive fields and then // recurse for all non-primitives. // // This is safe for cyclic or tree-like structs, up to a limit. Use the // MaxDepth method to adjust how deep you need it to recurse. // // obj must be a pointer. Only exported (public) fields can be set (thanks, // golang :/ ) Intended for tests, so will panic on bad input or unimplemented // fields. func (f *Fuzzer) Fuzz(obj interface{}) { v := reflect.ValueOf(obj) if v.Kind() != reflect.Ptr { panic("needed ptr!") } v = v.Elem() f.fuzzWithContext(v, 0) } // FuzzNoCustom is just like Fuzz, except that any custom fuzz function for // obj's type will not be called and obj will not be tested for fuzz.Interface // conformance. This applies only to obj and not other instances of obj's // type. // Not safe for cyclic or tree-like structs! // obj must be a pointer. Only exported (public) fields can be set (thanks, golang :/ ) // Intended for tests, so will panic on bad input or unimplemented fields. func (f *Fuzzer) FuzzNoCustom(obj interface{}) { v := reflect.ValueOf(obj) if v.Kind() != reflect.Ptr { panic("needed ptr!") } v = v.Elem() f.fuzzWithContext(v, flagNoCustomFuzz) } const ( // Do not try to find a custom fuzz function. Does not apply recursively. flagNoCustomFuzz uint64 = 1 << iota ) func (f *Fuzzer) fuzzWithContext(v reflect.Value, flags uint64) { fc := &fuzzerContext{fuzzer: f} fc.doFuzz(v, flags) } // fuzzerContext carries context about a single fuzzing run, which lets Fuzzer // be thread-safe. type fuzzerContext struct { fuzzer *Fuzzer curDepth int } func (fc *fuzzerContext) doFuzz(v reflect.Value, flags uint64) { if fc.curDepth >= fc.fuzzer.maxDepth { return } fc.curDepth++ defer func() { fc.curDepth-- }() if !v.CanSet() { return } if flags&flagNoCustomFuzz == 0 { // Check for both pointer and non-pointer custom functions. if v.CanAddr() && fc.tryCustom(v.Addr()) { return } if fc.tryCustom(v) { return } } if fn, ok := fillFuncMap[v.Kind()]; ok { fn(v, fc.fuzzer.r) return } switch v.Kind() { case reflect.Map: if fc.fuzzer.genShouldFill() { v.Set(reflect.MakeMap(v.Type())) n := fc.fuzzer.genElementCount() for i := 0; i < n; i++ { key := reflect.New(v.Type().Key()).Elem() fc.doFuzz(key, 0) val := reflect.New(v.Type().Elem()).Elem() fc.doFuzz(val, 0) v.SetMapIndex(key, val) } return } v.Set(reflect.Zero(v.Type())) case reflect.Ptr: if fc.fuzzer.genShouldFill() { v.Set(reflect.New(v.Type().Elem())) fc.doFuzz(v.Elem(), 0) return } v.Set(reflect.Zero(v.Type())) case reflect.Slice: if fc.fuzzer.genShouldFill() { n := fc.fuzzer.genElementCount() v.Set(reflect.MakeSlice(v.Type(), n, n)) for i := 0; i < n; i++ { fc.doFuzz(v.Index(i), 0) } return } v.Set(reflect.Zero(v.Type())) case reflect.Array: if fc.fuzzer.genShouldFill() { n := v.Len() for i := 0; i < n; i++ { fc.doFuzz(v.Index(i), 0) } return } v.Set(reflect.Zero(v.Type())) case reflect.Struct: for i := 0; i < v.NumField(); i++ { skipField := false fieldName := v.Type().Field(i).Name for _, pattern := range fc.fuzzer.skipFieldPatterns { if pattern.MatchString(fieldName) { skipField = true break } } if !skipField { fc.doFuzz(v.Field(i), 0) } } case reflect.Chan: fallthrough case reflect.Func: fallthrough case reflect.Interface: fallthrough default: panic(fmt.Sprintf("Can't handle %#v", v.Interface())) } } // tryCustom searches for custom handlers, and returns true iff it finds a match // and successfully randomizes v. func (fc *fuzzerContext) tryCustom(v reflect.Value) bool { // First: see if we have a fuzz function for it. doCustom, ok := fc.fuzzer.fuzzFuncs[v.Type()] if !ok { // Second: see if it can fuzz itself. if v.CanInterface() { intf := v.Interface() if fuzzable, ok := intf.(Interface); ok { fuzzable.Fuzz(Continue{fc: fc, Rand: fc.fuzzer.r}) return true } } // Finally: see if there is a default fuzz function. doCustom, ok = fc.fuzzer.defaultFuzzFuncs[v.Type()] if !ok { return false } } switch v.Kind() { case reflect.Ptr: if v.IsNil() { if !v.CanSet() { return false } v.Set(reflect.New(v.Type().Elem())) } case reflect.Map: if v.IsNil() { if !v.CanSet() { return false } v.Set(reflect.MakeMap(v.Type())) } default: return false } doCustom.Call([]reflect.Value{v, reflect.ValueOf(Continue{ fc: fc, Rand: fc.fuzzer.r, })}) return true } // Interface represents an object that knows how to fuzz itself. Any time we // find a type that implements this interface we will delegate the act of // fuzzing itself. type Interface interface { Fuzz(c Continue) } // Continue can be passed to custom fuzzing functions to allow them to use // the correct source of randomness and to continue fuzzing their members. type Continue struct { fc *fuzzerContext // For convenience, Continue implements rand.Rand via embedding. // Use this for generating any randomness if you want your fuzzing // to be repeatable for a given seed. *rand.Rand } // Fuzz continues fuzzing obj. obj must be a pointer. func (c Continue) Fuzz(obj interface{}) { v := reflect.ValueOf(obj) if v.Kind() != reflect.Ptr { panic("needed ptr!") } v = v.Elem() c.fc.doFuzz(v, 0) } // FuzzNoCustom continues fuzzing obj, except that any custom fuzz function for // obj's type will not be called and obj will not be tested for fuzz.Interface // conformance. This applies only to obj and not other instances of obj's // type. func (c Continue) FuzzNoCustom(obj interface{}) { v := reflect.ValueOf(obj) if v.Kind() != reflect.Ptr { panic("needed ptr!") } v = v.Elem() c.fc.doFuzz(v, flagNoCustomFuzz) } // RandString makes a random string up to 20 characters long. The returned string // may include a variety of (valid) UTF-8 encodings. func (c Continue) RandString() string { return randString(c.Rand) } // RandUint64 makes random 64 bit numbers. // Weirdly, rand doesn't have a function that gives you 64 random bits. func (c Continue) RandUint64() uint64 { return randUint64(c.Rand) } // RandBool returns true or false randomly. func (c Continue) RandBool() bool { return randBool(c.Rand) } func fuzzInt(v reflect.Value, r *rand.Rand) { v.SetInt(int64(randUint64(r))) } func fuzzUint(v reflect.Value, r *rand.Rand) { v.SetUint(randUint64(r)) } func fuzzTime(t *time.Time, c Continue) { var sec, nsec int64 // Allow for about 1000 years of random time values, which keeps things // like JSON parsing reasonably happy. sec = c.Rand.Int63n(1000 * 365 * 24 * 60 * 60) c.Fuzz(&nsec) *t = time.Unix(sec, nsec) } var fillFuncMap = map[reflect.Kind]func(reflect.Value, *rand.Rand){ reflect.Bool: func(v reflect.Value, r *rand.Rand) { v.SetBool(randBool(r)) }, reflect.Int: fuzzInt, reflect.Int8: fuzzInt, reflect.Int16: fuzzInt, reflect.Int32: fuzzInt, reflect.Int64: fuzzInt, reflect.Uint: fuzzUint, reflect.Uint8: fuzzUint, reflect.Uint16: fuzzUint, reflect.Uint32: fuzzUint, reflect.Uint64: fuzzUint, reflect.Uintptr: fuzzUint, reflect.Float32: func(v reflect.Value, r *rand.Rand) { v.SetFloat(float64(r.Float32())) }, reflect.Float64: func(v reflect.Value, r *rand.Rand) { v.SetFloat(r.Float64()) }, reflect.Complex64: func(v reflect.Value, r *rand.Rand) { v.SetComplex(complex128(complex(r.Float32(), r.Float32()))) }, reflect.Complex128: func(v reflect.Value, r *rand.Rand) { v.SetComplex(complex(r.Float64(), r.Float64())) }, reflect.String: func(v reflect.Value, r *rand.Rand) { v.SetString(randString(r)) }, reflect.UnsafePointer: func(v reflect.Value, r *rand.Rand) { panic("unimplemented") }, } // randBool returns true or false randomly. func randBool(r *rand.Rand) bool { return r.Int31()&(1<<30) == 0 } type int63nPicker interface { Int63n(int64) int64 } // UnicodeRange describes a sequential range of unicode characters. // Last must be numerically greater than First. type UnicodeRange struct { First, Last rune } // UnicodeRanges describes an arbitrary number of sequential ranges of unicode characters. // To be useful, each range must have at least one character (First <= Last) and // there must be at least one range. type UnicodeRanges []UnicodeRange // choose returns a random unicode character from the given range, using the // given randomness source. func (ur UnicodeRange) choose(r int63nPicker) rune { count := int64(ur.Last - ur.First + 1) return ur.First + rune(r.Int63n(count)) } // CustomStringFuzzFunc constructs a FuzzFunc which produces random strings. // Each character is selected from the range ur. If there are no characters // in the range (cr.Last < cr.First), this will panic. func (ur UnicodeRange) CustomStringFuzzFunc() func(s *string, c Continue) { ur.check() return func(s *string, c Continue) { *s = ur.randString(c.Rand) } } // check is a function that used to check whether the first of ur(UnicodeRange) // is greater than the last one. func (ur UnicodeRange) check() { if ur.Last < ur.First { panic("The last encoding must be greater than the first one.") } } // randString of UnicodeRange makes a random string up to 20 characters long. // Each character is selected form ur(UnicodeRange). func (ur UnicodeRange) randString(r *rand.Rand) string { n := r.Intn(20) sb := strings.Builder{} sb.Grow(n) for i := 0; i < n; i++ { sb.WriteRune(ur.choose(r)) } return sb.String() } // defaultUnicodeRanges sets a default unicode range when user do not set // CustomStringFuzzFunc() but wants fuzz string. var defaultUnicodeRanges = UnicodeRanges{ {' ', '~'}, // ASCII characters {'\u00a0', '\u02af'}, // Multi-byte encoded characters {'\u4e00', '\u9fff'}, // Common CJK (even longer encodings) } // CustomStringFuzzFunc constructs a FuzzFunc which produces random strings. // Each character is selected from one of the ranges of ur(UnicodeRanges). // Each range has an equal probability of being chosen. If there are no ranges, // or a selected range has no characters (.Last < .First), this will panic. // Do not modify any of the ranges in ur after calling this function. func (ur UnicodeRanges) CustomStringFuzzFunc() func(s *string, c Continue) { // Check unicode ranges slice is empty. if len(ur) == 0 { panic("UnicodeRanges is empty.") } // if not empty, each range should be checked. for i := range ur { ur[i].check() } return func(s *string, c Continue) { *s = ur.randString(c.Rand) } } // randString of UnicodeRanges makes a random string up to 20 characters long. // Each character is selected form one of the ranges of ur(UnicodeRanges), // and each range has an equal probability of being chosen. func (ur UnicodeRanges) randString(r *rand.Rand) string { n := r.Intn(20) sb := strings.Builder{} sb.Grow(n) for i := 0; i < n; i++ { sb.WriteRune(ur[r.Intn(len(ur))].choose(r)) } return sb.String() } // randString makes a random string up to 20 characters long. The returned string // may include a variety of (valid) UTF-8 encodings. func randString(r *rand.Rand) string { return defaultUnicodeRanges.randString(r) } // randUint64 makes random 64 bit numbers. // Weirdly, rand doesn't have a function that gives you 64 random bits. func randUint64(r *rand.Rand) uint64 { return uint64(r.Uint32())<<32 | uint64(r.Uint32()) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/gofuzz/doc.go
vendor/github.com/google/gofuzz/doc.go
/* Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package fuzz is a library for populating go objects with random values. package fuzz
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/gofuzz/bytesource/bytesource.go
vendor/github.com/google/gofuzz/bytesource/bytesource.go
/* Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package bytesource provides a rand.Source64 that is determined by a slice of bytes. package bytesource import ( "bytes" "encoding/binary" "io" "math/rand" ) // ByteSource implements rand.Source64 determined by a slice of bytes. The random numbers are // generated from each 8 bytes in the slice, until the last bytes are consumed, from which a // fallback pseudo random source is created in case more random numbers are required. // It also exposes a `bytes.Reader` API, which lets callers consume the bytes directly. type ByteSource struct { *bytes.Reader fallback rand.Source } // New returns a new ByteSource from a given slice of bytes. func New(input []byte) *ByteSource { s := &ByteSource{ Reader: bytes.NewReader(input), fallback: rand.NewSource(0), } if len(input) > 0 { s.fallback = rand.NewSource(int64(s.consumeUint64())) } return s } func (s *ByteSource) Uint64() uint64 { // Return from input if it was not exhausted. if s.Len() > 0 { return s.consumeUint64() } // Input was exhausted, return random number from fallback (in this case fallback should not be // nil). Try first having a Uint64 output (Should work in current rand implementation), // otherwise return a conversion of Int63. if s64, ok := s.fallback.(rand.Source64); ok { return s64.Uint64() } return uint64(s.fallback.Int63()) } func (s *ByteSource) Int63() int64 { return int64(s.Uint64() >> 1) } func (s *ByteSource) Seed(seed int64) { s.fallback = rand.NewSource(seed) s.Reader = bytes.NewReader(nil) } // consumeUint64 reads 8 bytes from the input and convert them to a uint64. It assumes that the the // bytes reader is not empty. func (s *ByteSource) consumeUint64() uint64 { var bytes [8]byte _, err := s.Read(bytes[:]) if err != nil && err != io.EOF { panic("failed reading source") // Should not happen. } return binary.BigEndian.Uint64(bytes[:]) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/uuid/version1.go
vendor/github.com/google/uuid/version1.go
// Copyright 2016 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. package uuid import ( "encoding/binary" ) // NewUUID returns a Version 1 UUID based on the current NodeID and clock // sequence, and the current time. If the NodeID has not been set by SetNodeID // or SetNodeInterface then it will be set automatically. If the NodeID cannot // be set NewUUID returns nil. If clock sequence has not been set by // SetClockSequence then it will be set automatically. If GetTime fails to // return the current NewUUID returns nil and an error. // // In most cases, New should be used. func NewUUID() (UUID, error) { var uuid UUID now, seq, err := GetTime() if err != nil { return uuid, err } timeLow := uint32(now & 0xffffffff) timeMid := uint16((now >> 32) & 0xffff) timeHi := uint16((now >> 48) & 0x0fff) timeHi |= 0x1000 // Version 1 binary.BigEndian.PutUint32(uuid[0:], timeLow) binary.BigEndian.PutUint16(uuid[4:], timeMid) binary.BigEndian.PutUint16(uuid[6:], timeHi) binary.BigEndian.PutUint16(uuid[8:], seq) nodeMu.Lock() if nodeID == zeroID { setNodeInterface("") } copy(uuid[10:], nodeID[:]) nodeMu.Unlock() return uuid, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/uuid/time.go
vendor/github.com/google/uuid/time.go
// Copyright 2016 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. package uuid import ( "encoding/binary" "sync" "time" ) // A Time represents a time as the number of 100's of nanoseconds since 15 Oct // 1582. type Time int64 const ( lillian = 2299160 // Julian day of 15 Oct 1582 unix = 2440587 // Julian day of 1 Jan 1970 epoch = unix - lillian // Days between epochs g1582 = epoch * 86400 // seconds between epochs g1582ns100 = g1582 * 10000000 // 100s of a nanoseconds between epochs ) var ( timeMu sync.Mutex lasttime uint64 // last time we returned clockSeq uint16 // clock sequence for this run timeNow = time.Now // for testing ) // UnixTime converts t the number of seconds and nanoseconds using the Unix // epoch of 1 Jan 1970. func (t Time) UnixTime() (sec, nsec int64) { sec = int64(t - g1582ns100) nsec = (sec % 10000000) * 100 sec /= 10000000 return sec, nsec } // GetTime returns the current Time (100s of nanoseconds since 15 Oct 1582) and // clock sequence as well as adjusting the clock sequence as needed. An error // is returned if the current time cannot be determined. func GetTime() (Time, uint16, error) { defer timeMu.Unlock() timeMu.Lock() return getTime() } func getTime() (Time, uint16, error) { t := timeNow() // If we don't have a clock sequence already, set one. if clockSeq == 0 { setClockSequence(-1) } now := uint64(t.UnixNano()/100) + g1582ns100 // If time has gone backwards with this clock sequence then we // increment the clock sequence if now <= lasttime { clockSeq = ((clockSeq + 1) & 0x3fff) | 0x8000 } lasttime = now return Time(now), clockSeq, nil } // ClockSequence returns the current clock sequence, generating one if not // already set. The clock sequence is only used for Version 1 UUIDs. // // The uuid package does not use global static storage for the clock sequence or // the last time a UUID was generated. Unless SetClockSequence is used, a new // random clock sequence is generated the first time a clock sequence is // requested by ClockSequence, GetTime, or NewUUID. (section 4.2.1.1) func ClockSequence() int { defer timeMu.Unlock() timeMu.Lock() return clockSequence() } func clockSequence() int { if clockSeq == 0 { setClockSequence(-1) } return int(clockSeq & 0x3fff) } // SetClockSequence sets the clock sequence to the lower 14 bits of seq. Setting to // -1 causes a new sequence to be generated. func SetClockSequence(seq int) { defer timeMu.Unlock() timeMu.Lock() setClockSequence(seq) } func setClockSequence(seq int) { if seq == -1 { var b [2]byte randomBits(b[:]) // clock sequence seq = int(b[0])<<8 | int(b[1]) } oldSeq := clockSeq clockSeq = uint16(seq&0x3fff) | 0x8000 // Set our variant if oldSeq != clockSeq { lasttime = 0 } } // Time returns the time in 100s of nanoseconds since 15 Oct 1582 encoded in // uuid. The time is only defined for version 1, 2, 6 and 7 UUIDs. func (uuid UUID) Time() Time { var t Time switch uuid.Version() { case 6: time := binary.BigEndian.Uint64(uuid[:8]) // Ignore uuid[6] version b0110 t = Time(time) case 7: time := binary.BigEndian.Uint64(uuid[:8]) t = Time((time>>16)*10000 + g1582ns100) default: // forward compatible time := int64(binary.BigEndian.Uint32(uuid[0:4])) time |= int64(binary.BigEndian.Uint16(uuid[4:6])) << 32 time |= int64(binary.BigEndian.Uint16(uuid[6:8])&0xfff) << 48 t = Time(time) } return t } // ClockSequence returns the clock sequence encoded in uuid. // The clock sequence is only well defined for version 1 and 2 UUIDs. func (uuid UUID) ClockSequence() int { return int(binary.BigEndian.Uint16(uuid[8:10])) & 0x3fff }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/uuid/uuid.go
vendor/github.com/google/uuid/uuid.go
// Copyright 2018 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. package uuid import ( "bytes" "crypto/rand" "encoding/hex" "errors" "fmt" "io" "strings" "sync" ) // A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC // 4122. type UUID [16]byte // A Version represents a UUID's version. type Version byte // A Variant represents a UUID's variant. type Variant byte // Constants returned by Variant. const ( Invalid = Variant(iota) // Invalid UUID RFC4122 // The variant specified in RFC4122 Reserved // Reserved, NCS backward compatibility. Microsoft // Reserved, Microsoft Corporation backward compatibility. Future // Reserved for future definition. ) const randPoolSize = 16 * 16 var ( rander = rand.Reader // random function poolEnabled = false poolMu sync.Mutex poolPos = randPoolSize // protected with poolMu pool [randPoolSize]byte // protected with poolMu ) type invalidLengthError struct{ len int } func (err invalidLengthError) Error() string { return fmt.Sprintf("invalid UUID length: %d", err.len) } // IsInvalidLengthError is matcher function for custom error invalidLengthError func IsInvalidLengthError(err error) bool { _, ok := err.(invalidLengthError) return ok } // Parse decodes s into a UUID or returns an error if it cannot be parsed. Both // the standard UUID forms defined in RFC 4122 // (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) are decoded. In addition, // Parse accepts non-standard strings such as the raw hex encoding // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx and 38 byte "Microsoft style" encodings, // e.g. {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}. Only the middle 36 bytes are // examined in the latter case. Parse should not be used to validate strings as // it parses non-standard encodings as indicated above. func Parse(s string) (UUID, error) { var uuid UUID switch len(s) { // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx case 36: // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx case 36 + 9: if !strings.EqualFold(s[:9], "urn:uuid:") { return uuid, fmt.Errorf("invalid urn prefix: %q", s[:9]) } s = s[9:] // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} case 36 + 2: s = s[1:] // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx case 32: var ok bool for i := range uuid { uuid[i], ok = xtob(s[i*2], s[i*2+1]) if !ok { return uuid, errors.New("invalid UUID format") } } return uuid, nil default: return uuid, invalidLengthError{len(s)} } // s is now at least 36 bytes long // it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' { return uuid, errors.New("invalid UUID format") } for i, x := range [16]int{ 0, 2, 4, 6, 9, 11, 14, 16, 19, 21, 24, 26, 28, 30, 32, 34, } { v, ok := xtob(s[x], s[x+1]) if !ok { return uuid, errors.New("invalid UUID format") } uuid[i] = v } return uuid, nil } // ParseBytes is like Parse, except it parses a byte slice instead of a string. func ParseBytes(b []byte) (UUID, error) { var uuid UUID switch len(b) { case 36: // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx case 36 + 9: // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx if !bytes.EqualFold(b[:9], []byte("urn:uuid:")) { return uuid, fmt.Errorf("invalid urn prefix: %q", b[:9]) } b = b[9:] case 36 + 2: // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} b = b[1:] case 32: // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx var ok bool for i := 0; i < 32; i += 2 { uuid[i/2], ok = xtob(b[i], b[i+1]) if !ok { return uuid, errors.New("invalid UUID format") } } return uuid, nil default: return uuid, invalidLengthError{len(b)} } // s is now at least 36 bytes long // it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx if b[8] != '-' || b[13] != '-' || b[18] != '-' || b[23] != '-' { return uuid, errors.New("invalid UUID format") } for i, x := range [16]int{ 0, 2, 4, 6, 9, 11, 14, 16, 19, 21, 24, 26, 28, 30, 32, 34, } { v, ok := xtob(b[x], b[x+1]) if !ok { return uuid, errors.New("invalid UUID format") } uuid[i] = v } return uuid, nil } // MustParse is like Parse but panics if the string cannot be parsed. // It simplifies safe initialization of global variables holding compiled UUIDs. func MustParse(s string) UUID { uuid, err := Parse(s) if err != nil { panic(`uuid: Parse(` + s + `): ` + err.Error()) } return uuid } // FromBytes creates a new UUID from a byte slice. Returns an error if the slice // does not have a length of 16. The bytes are copied from the slice. func FromBytes(b []byte) (uuid UUID, err error) { err = uuid.UnmarshalBinary(b) return uuid, err } // Must returns uuid if err is nil and panics otherwise. func Must(uuid UUID, err error) UUID { if err != nil { panic(err) } return uuid } // Validate returns an error if s is not a properly formatted UUID in one of the following formats: // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} // It returns an error if the format is invalid, otherwise nil. func Validate(s string) error { switch len(s) { // Standard UUID format case 36: // UUID with "urn:uuid:" prefix case 36 + 9: if !strings.EqualFold(s[:9], "urn:uuid:") { return fmt.Errorf("invalid urn prefix: %q", s[:9]) } s = s[9:] // UUID enclosed in braces case 36 + 2: if s[0] != '{' || s[len(s)-1] != '}' { return fmt.Errorf("invalid bracketed UUID format") } s = s[1 : len(s)-1] // UUID without hyphens case 32: for i := 0; i < len(s); i += 2 { _, ok := xtob(s[i], s[i+1]) if !ok { return errors.New("invalid UUID format") } } default: return invalidLengthError{len(s)} } // Check for standard UUID format if len(s) == 36 { if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' { return errors.New("invalid UUID format") } for _, x := range []int{0, 2, 4, 6, 9, 11, 14, 16, 19, 21, 24, 26, 28, 30, 32, 34} { if _, ok := xtob(s[x], s[x+1]); !ok { return errors.New("invalid UUID format") } } } return nil } // String returns the string form of uuid, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx // , or "" if uuid is invalid. func (uuid UUID) String() string { var buf [36]byte encodeHex(buf[:], uuid) return string(buf[:]) } // URN returns the RFC 2141 URN form of uuid, // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, or "" if uuid is invalid. func (uuid UUID) URN() string { var buf [36 + 9]byte copy(buf[:], "urn:uuid:") encodeHex(buf[9:], uuid) return string(buf[:]) } func encodeHex(dst []byte, uuid UUID) { hex.Encode(dst, uuid[:4]) dst[8] = '-' hex.Encode(dst[9:13], uuid[4:6]) dst[13] = '-' hex.Encode(dst[14:18], uuid[6:8]) dst[18] = '-' hex.Encode(dst[19:23], uuid[8:10]) dst[23] = '-' hex.Encode(dst[24:], uuid[10:]) } // Variant returns the variant encoded in uuid. func (uuid UUID) Variant() Variant { switch { case (uuid[8] & 0xc0) == 0x80: return RFC4122 case (uuid[8] & 0xe0) == 0xc0: return Microsoft case (uuid[8] & 0xe0) == 0xe0: return Future default: return Reserved } } // Version returns the version of uuid. func (uuid UUID) Version() Version { return Version(uuid[6] >> 4) } func (v Version) String() string { if v > 15 { return fmt.Sprintf("BAD_VERSION_%d", v) } return fmt.Sprintf("VERSION_%d", v) } func (v Variant) String() string { switch v { case RFC4122: return "RFC4122" case Reserved: return "Reserved" case Microsoft: return "Microsoft" case Future: return "Future" case Invalid: return "Invalid" } return fmt.Sprintf("BadVariant%d", int(v)) } // SetRand sets the random number generator to r, which implements io.Reader. // If r.Read returns an error when the package requests random data then // a panic will be issued. // // Calling SetRand with nil sets the random number generator to the default // generator. func SetRand(r io.Reader) { if r == nil { rander = rand.Reader return } rander = r } // EnableRandPool enables internal randomness pool used for Random // (Version 4) UUID generation. The pool contains random bytes read from // the random number generator on demand in batches. Enabling the pool // may improve the UUID generation throughput significantly. // // Since the pool is stored on the Go heap, this feature may be a bad fit // for security sensitive applications. // // Both EnableRandPool and DisableRandPool are not thread-safe and should // only be called when there is no possibility that New or any other // UUID Version 4 generation function will be called concurrently. func EnableRandPool() { poolEnabled = true } // DisableRandPool disables the randomness pool if it was previously // enabled with EnableRandPool. // // Both EnableRandPool and DisableRandPool are not thread-safe and should // only be called when there is no possibility that New or any other // UUID Version 4 generation function will be called concurrently. func DisableRandPool() { poolEnabled = false defer poolMu.Unlock() poolMu.Lock() poolPos = randPoolSize } // UUIDs is a slice of UUID types. type UUIDs []UUID // Strings returns a string slice containing the string form of each UUID in uuids. func (uuids UUIDs) Strings() []string { var uuidStrs = make([]string, len(uuids)) for i, uuid := range uuids { uuidStrs[i] = uuid.String() } return uuidStrs }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/uuid/version6.go
vendor/github.com/google/uuid/version6.go
// 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. package uuid import "encoding/binary" // UUID version 6 is a field-compatible version of UUIDv1, reordered for improved DB locality. // It is expected that UUIDv6 will primarily be used in contexts where there are existing v1 UUIDs. // Systems that do not involve legacy UUIDv1 SHOULD consider using UUIDv7 instead. // // see https://datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format-03#uuidv6 // // NewV6 returns a Version 6 UUID based on the current NodeID and clock // sequence, and the current time. If the NodeID has not been set by SetNodeID // or SetNodeInterface then it will be set automatically. If the NodeID cannot // be set NewV6 set NodeID is random bits automatically . If clock sequence has not been set by // SetClockSequence then it will be set automatically. If GetTime fails to // return the current NewV6 returns Nil and an error. func NewV6() (UUID, error) { var uuid UUID now, seq, err := GetTime() if err != nil { return uuid, err } /* 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | time_high | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | time_mid | time_low_and_version | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |clk_seq_hi_res | clk_seq_low | node (0-1) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | node (2-5) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ binary.BigEndian.PutUint64(uuid[0:], uint64(now)) binary.BigEndian.PutUint16(uuid[8:], seq) uuid[6] = 0x60 | (uuid[6] & 0x0F) uuid[8] = 0x80 | (uuid[8] & 0x3F) nodeMu.Lock() if nodeID == zeroID { setNodeInterface("") } copy(uuid[10:], nodeID[:]) nodeMu.Unlock() return uuid, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/uuid/node_net.go
vendor/github.com/google/uuid/node_net.go
// Copyright 2017 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. // +build !js package uuid import "net" var interfaces []net.Interface // cached list of interfaces // getHardwareInterface returns the name and hardware address of interface name. // If name is "" then the name and hardware address of one of the system's // interfaces is returned. If no interfaces are found (name does not exist or // there are no interfaces) then "", nil is returned. // // Only addresses of at least 6 bytes are returned. func getHardwareInterface(name string) (string, []byte) { if interfaces == nil { var err error interfaces, err = net.Interfaces() if err != nil { return "", nil } } for _, ifs := range interfaces { if len(ifs.HardwareAddr) >= 6 && (name == "" || name == ifs.Name) { return ifs.Name, ifs.HardwareAddr } } return "", nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/uuid/node.go
vendor/github.com/google/uuid/node.go
// Copyright 2016 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. package uuid import ( "sync" ) var ( nodeMu sync.Mutex ifname string // name of interface being used nodeID [6]byte // hardware for version 1 UUIDs zeroID [6]byte // nodeID with only 0's ) // NodeInterface returns the name of the interface from which the NodeID was // derived. The interface "user" is returned if the NodeID was set by // SetNodeID. func NodeInterface() string { defer nodeMu.Unlock() nodeMu.Lock() return ifname } // SetNodeInterface selects the hardware address to be used for Version 1 UUIDs. // If name is "" then the first usable interface found will be used or a random // Node ID will be generated. If a named interface cannot be found then false // is returned. // // SetNodeInterface never fails when name is "". func SetNodeInterface(name string) bool { defer nodeMu.Unlock() nodeMu.Lock() return setNodeInterface(name) } func setNodeInterface(name string) bool { iname, addr := getHardwareInterface(name) // null implementation for js if iname != "" && addr != nil { ifname = iname copy(nodeID[:], addr) return true } // We found no interfaces with a valid hardware address. If name // does not specify a specific interface generate a random Node ID // (section 4.1.6) if name == "" { ifname = "random" randomBits(nodeID[:]) return true } return false } // NodeID returns a slice of a copy of the current Node ID, setting the Node ID // if not already set. func NodeID() []byte { defer nodeMu.Unlock() nodeMu.Lock() if nodeID == zeroID { setNodeInterface("") } nid := nodeID return nid[:] } // SetNodeID sets the Node ID to be used for Version 1 UUIDs. The first 6 bytes // of id are used. If id is less than 6 bytes then false is returned and the // Node ID is not set. func SetNodeID(id []byte) bool { if len(id) < 6 { return false } defer nodeMu.Unlock() nodeMu.Lock() copy(nodeID[:], id) ifname = "user" return true } // NodeID returns the 6 byte node id encoded in uuid. It returns nil if uuid is // not valid. The NodeID is only well defined for version 1 and 2 UUIDs. func (uuid UUID) NodeID() []byte { var node [6]byte copy(node[:], uuid[10:]) return node[:] }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/uuid/hash.go
vendor/github.com/google/uuid/hash.go
// Copyright 2016 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. package uuid import ( "crypto/md5" "crypto/sha1" "hash" ) // Well known namespace IDs and UUIDs var ( NameSpaceDNS = Must(Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8")) NameSpaceURL = Must(Parse("6ba7b811-9dad-11d1-80b4-00c04fd430c8")) NameSpaceOID = Must(Parse("6ba7b812-9dad-11d1-80b4-00c04fd430c8")) NameSpaceX500 = Must(Parse("6ba7b814-9dad-11d1-80b4-00c04fd430c8")) Nil UUID // empty UUID, all zeros // The Max UUID is special form of UUID that is specified to have all 128 bits set to 1. Max = UUID{ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, } ) // NewHash returns a new UUID derived from the hash of space concatenated with // data generated by h. The hash should be at least 16 byte in length. The // first 16 bytes of the hash are used to form the UUID. The version of the // UUID will be the lower 4 bits of version. NewHash is used to implement // NewMD5 and NewSHA1. func NewHash(h hash.Hash, space UUID, data []byte, version int) UUID { h.Reset() h.Write(space[:]) //nolint:errcheck h.Write(data) //nolint:errcheck s := h.Sum(nil) var uuid UUID copy(uuid[:], s) uuid[6] = (uuid[6] & 0x0f) | uint8((version&0xf)<<4) uuid[8] = (uuid[8] & 0x3f) | 0x80 // RFC 4122 variant return uuid } // NewMD5 returns a new MD5 (Version 3) UUID based on the // supplied name space and data. It is the same as calling: // // NewHash(md5.New(), space, data, 3) func NewMD5(space UUID, data []byte) UUID { return NewHash(md5.New(), space, data, 3) } // NewSHA1 returns a new SHA1 (Version 5) UUID based on the // supplied name space and data. It is the same as calling: // // NewHash(sha1.New(), space, data, 5) func NewSHA1(space UUID, data []byte) UUID { return NewHash(sha1.New(), space, data, 5) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/uuid/util.go
vendor/github.com/google/uuid/util.go
// Copyright 2016 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. package uuid import ( "io" ) // randomBits completely fills slice b with random data. func randomBits(b []byte) { if _, err := io.ReadFull(rander, b); err != nil { panic(err.Error()) // rand should never fail } } // xvalues returns the value of a byte as a hexadecimal digit or 255. var xvalues = [256]byte{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, } // xtob converts hex characters x1 and x2 into a byte. func xtob(x1, x2 byte) (byte, bool) { b1 := xvalues[x1] b2 := xvalues[x2] return (b1 << 4) | b2, b1 != 255 && b2 != 255 }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/uuid/marshal.go
vendor/github.com/google/uuid/marshal.go
// Copyright 2016 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. package uuid import "fmt" // MarshalText implements encoding.TextMarshaler. func (uuid UUID) MarshalText() ([]byte, error) { var js [36]byte encodeHex(js[:], uuid) return js[:], nil } // UnmarshalText implements encoding.TextUnmarshaler. func (uuid *UUID) UnmarshalText(data []byte) error { id, err := ParseBytes(data) if err != nil { return err } *uuid = id return nil } // MarshalBinary implements encoding.BinaryMarshaler. func (uuid UUID) MarshalBinary() ([]byte, error) { return uuid[:], nil } // UnmarshalBinary implements encoding.BinaryUnmarshaler. func (uuid *UUID) UnmarshalBinary(data []byte) error { if len(data) != 16 { return fmt.Errorf("invalid UUID (got %d bytes)", len(data)) } copy(uuid[:], data) return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/uuid/node_js.go
vendor/github.com/google/uuid/node_js.go
// Copyright 2017 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. // +build js package uuid // getHardwareInterface returns nil values for the JS version of the code. // This removes the "net" dependency, because it is not used in the browser. // Using the "net" library inflates the size of the transpiled JS code by 673k bytes. func getHardwareInterface(name string) (string, []byte) { return "", nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/uuid/sql.go
vendor/github.com/google/uuid/sql.go
// Copyright 2016 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. package uuid import ( "database/sql/driver" "fmt" ) // Scan implements sql.Scanner so UUIDs can be read from databases transparently. // Currently, database types that map to string and []byte are supported. Please // consult database-specific driver documentation for matching types. func (uuid *UUID) Scan(src interface{}) error { switch src := src.(type) { case nil: return nil case string: // if an empty UUID comes from a table, we return a null UUID if src == "" { return nil } // see Parse for required string format u, err := Parse(src) if err != nil { return fmt.Errorf("Scan: %v", err) } *uuid = u case []byte: // if an empty UUID comes from a table, we return a null UUID if len(src) == 0 { return nil } // assumes a simple slice of bytes if 16 bytes // otherwise attempts to parse if len(src) != 16 { return uuid.Scan(string(src)) } copy((*uuid)[:], src) default: return fmt.Errorf("Scan: unable to scan type %T into UUID", src) } return nil } // Value implements sql.Valuer so that UUIDs can be written to databases // transparently. Currently, UUIDs map to strings. Please consult // database-specific driver documentation for matching types. func (uuid UUID) Value() (driver.Value, error) { return uuid.String(), nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/uuid/version7.go
vendor/github.com/google/uuid/version7.go
// 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. package uuid import ( "io" ) // UUID version 7 features a time-ordered value field derived from the widely // implemented and well known Unix Epoch timestamp source, // the number of milliseconds seconds since midnight 1 Jan 1970 UTC, leap seconds excluded. // As well as improved entropy characteristics over versions 1 or 6. // // see https://datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format-03#name-uuid-version-7 // // Implementations SHOULD utilize UUID version 7 over UUID version 1 and 6 if possible. // // NewV7 returns a Version 7 UUID based on the current time(Unix Epoch). // Uses the randomness pool if it was enabled with EnableRandPool. // On error, NewV7 returns Nil and an error func NewV7() (UUID, error) { uuid, err := NewRandom() if err != nil { return uuid, err } makeV7(uuid[:]) return uuid, nil } // NewV7FromReader returns a Version 7 UUID based on the current time(Unix Epoch). // it use NewRandomFromReader fill random bits. // On error, NewV7FromReader returns Nil and an error. func NewV7FromReader(r io.Reader) (UUID, error) { uuid, err := NewRandomFromReader(r) if err != nil { return uuid, err } makeV7(uuid[:]) return uuid, nil } // makeV7 fill 48 bits time (uuid[0] - uuid[5]), set version b0111 (uuid[6]) // uuid[8] already has the right version number (Variant is 10) // see function NewV7 and NewV7FromReader func makeV7(uuid []byte) { /* 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | unix_ts_ms | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | unix_ts_ms | ver | rand_a (12 bit seq) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |var| rand_b | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | rand_b | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ _ = uuid[15] // bounds check t, s := getV7Time() uuid[0] = byte(t >> 40) uuid[1] = byte(t >> 32) uuid[2] = byte(t >> 24) uuid[3] = byte(t >> 16) uuid[4] = byte(t >> 8) uuid[5] = byte(t) uuid[6] = 0x70 | (0x0F & byte(s>>8)) uuid[7] = byte(s) } // lastV7time is the last time we returned stored as: // // 52 bits of time in milliseconds since epoch // 12 bits of (fractional nanoseconds) >> 8 var lastV7time int64 const nanoPerMilli = 1000000 // getV7Time returns the time in milliseconds and nanoseconds / 256. // The returned (milli << 12 + seq) is guarenteed to be greater than // (milli << 12 + seq) returned by any previous call to getV7Time. func getV7Time() (milli, seq int64) { timeMu.Lock() defer timeMu.Unlock() nano := timeNow().UnixNano() milli = nano / nanoPerMilli // Sequence number is between 0 and 3906 (nanoPerMilli>>8) seq = (nano - milli*nanoPerMilli) >> 8 now := milli<<12 + seq if now <= lastV7time { now = lastV7time + 1 milli = now >> 12 seq = now & 0xfff } lastV7time = now return milli, seq }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/uuid/dce.go
vendor/github.com/google/uuid/dce.go
// Copyright 2016 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. package uuid import ( "encoding/binary" "fmt" "os" ) // A Domain represents a Version 2 domain type Domain byte // Domain constants for DCE Security (Version 2) UUIDs. const ( Person = Domain(0) Group = Domain(1) Org = Domain(2) ) // NewDCESecurity returns a DCE Security (Version 2) UUID. // // The domain should be one of Person, Group or Org. // On a POSIX system the id should be the users UID for the Person // domain and the users GID for the Group. The meaning of id for // the domain Org or on non-POSIX systems is site defined. // // For a given domain/id pair the same token may be returned for up to // 7 minutes and 10 seconds. func NewDCESecurity(domain Domain, id uint32) (UUID, error) { uuid, err := NewUUID() if err == nil { uuid[6] = (uuid[6] & 0x0f) | 0x20 // Version 2 uuid[9] = byte(domain) binary.BigEndian.PutUint32(uuid[0:], id) } return uuid, err } // NewDCEPerson returns a DCE Security (Version 2) UUID in the person // domain with the id returned by os.Getuid. // // NewDCESecurity(Person, uint32(os.Getuid())) func NewDCEPerson() (UUID, error) { return NewDCESecurity(Person, uint32(os.Getuid())) } // NewDCEGroup returns a DCE Security (Version 2) UUID in the group // domain with the id returned by os.Getgid. // // NewDCESecurity(Group, uint32(os.Getgid())) func NewDCEGroup() (UUID, error) { return NewDCESecurity(Group, uint32(os.Getgid())) } // Domain returns the domain for a Version 2 UUID. Domains are only defined // for Version 2 UUIDs. func (uuid UUID) Domain() Domain { return Domain(uuid[9]) } // ID returns the id for a Version 2 UUID. IDs are only defined for Version 2 // UUIDs. func (uuid UUID) ID() uint32 { return binary.BigEndian.Uint32(uuid[0:4]) } func (d Domain) String() string { switch d { case Person: return "Person" case Group: return "Group" case Org: return "Org" } return fmt.Sprintf("Domain%d", int(d)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/uuid/version4.go
vendor/github.com/google/uuid/version4.go
// Copyright 2016 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. package uuid import "io" // New creates a new random UUID or panics. New is equivalent to // the expression // // uuid.Must(uuid.NewRandom()) func New() UUID { return Must(NewRandom()) } // NewString creates a new random UUID and returns it as a string or panics. // NewString is equivalent to the expression // // uuid.New().String() func NewString() string { return Must(NewRandom()).String() } // NewRandom returns a Random (Version 4) UUID. // // The strength of the UUIDs is based on the strength of the crypto/rand // package. // // Uses the randomness pool if it was enabled with EnableRandPool. // // A note about uniqueness derived from the UUID Wikipedia entry: // // Randomly generated UUIDs have 122 random bits. One's annual risk of being // hit by a meteorite is estimated to be one chance in 17 billion, that // means the probability is about 0.00000000006 (6 × 10−11), // equivalent to the odds of creating a few tens of trillions of UUIDs in a // year and having one duplicate. func NewRandom() (UUID, error) { if !poolEnabled { return NewRandomFromReader(rander) } return newRandomFromPool() } // NewRandomFromReader returns a UUID based on bytes read from a given io.Reader. func NewRandomFromReader(r io.Reader) (UUID, error) { var uuid UUID _, err := io.ReadFull(r, uuid[:]) if err != nil { return Nil, err } uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4 uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10 return uuid, nil } func newRandomFromPool() (UUID, error) { var uuid UUID poolMu.Lock() if poolPos == randPoolSize { _, err := io.ReadFull(rander, pool[:]) if err != nil { poolMu.Unlock() return Nil, err } poolPos = 0 } copy(uuid[:], pool[poolPos:(poolPos+16)]) poolPos += 16 poolMu.Unlock() uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4 uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10 return uuid, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/uuid/null.go
vendor/github.com/google/uuid/null.go
// Copyright 2021 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. package uuid import ( "bytes" "database/sql/driver" "encoding/json" "fmt" ) var jsonNull = []byte("null") // NullUUID represents a UUID that may be null. // NullUUID implements the SQL driver.Scanner interface so // it can be used as a scan destination: // // var u uuid.NullUUID // err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&u) // ... // if u.Valid { // // use u.UUID // } else { // // NULL value // } // type NullUUID struct { UUID UUID Valid bool // Valid is true if UUID is not NULL } // Scan implements the SQL driver.Scanner interface. func (nu *NullUUID) Scan(value interface{}) error { if value == nil { nu.UUID, nu.Valid = Nil, false return nil } err := nu.UUID.Scan(value) if err != nil { nu.Valid = false return err } nu.Valid = true return nil } // Value implements the driver Valuer interface. func (nu NullUUID) Value() (driver.Value, error) { if !nu.Valid { return nil, nil } // Delegate to UUID Value function return nu.UUID.Value() } // MarshalBinary implements encoding.BinaryMarshaler. func (nu NullUUID) MarshalBinary() ([]byte, error) { if nu.Valid { return nu.UUID[:], nil } return []byte(nil), nil } // UnmarshalBinary implements encoding.BinaryUnmarshaler. func (nu *NullUUID) UnmarshalBinary(data []byte) error { if len(data) != 16 { return fmt.Errorf("invalid UUID (got %d bytes)", len(data)) } copy(nu.UUID[:], data) nu.Valid = true return nil } // MarshalText implements encoding.TextMarshaler. func (nu NullUUID) MarshalText() ([]byte, error) { if nu.Valid { return nu.UUID.MarshalText() } return jsonNull, nil } // UnmarshalText implements encoding.TextUnmarshaler. func (nu *NullUUID) UnmarshalText(data []byte) error { id, err := ParseBytes(data) if err != nil { nu.Valid = false return err } nu.UUID = id nu.Valid = true return nil } // MarshalJSON implements json.Marshaler. func (nu NullUUID) MarshalJSON() ([]byte, error) { if nu.Valid { return json.Marshal(nu.UUID) } return jsonNull, nil } // UnmarshalJSON implements json.Unmarshaler. func (nu *NullUUID) UnmarshalJSON(data []byte) error { if bytes.Equal(data, jsonNull) { *nu = NullUUID{} return nil // valid null UUID } err := json.Unmarshal(data, &nu.UUID) nu.Valid = 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/vendor/github.com/google/uuid/doc.go
vendor/github.com/google/uuid/doc.go
// Copyright 2016 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. // Package uuid generates and inspects UUIDs. // // UUIDs are based on RFC 4122 and DCE 1.1: Authentication and Security // Services. // // A UUID is a 16 byte (128 bit) array. UUIDs may be used as keys to // maps or compared directly. package uuid
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/btree/btree.go
vendor/github.com/google/btree/btree.go
// Copyright 2014 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build !go1.18 // +build !go1.18 // Package btree implements in-memory B-Trees of arbitrary degree. // // btree implements an in-memory B-Tree for use as an ordered data structure. // It is not meant for persistent storage solutions. // // It has a flatter structure than an equivalent red-black or other binary tree, // which in some cases yields better memory usage and/or performance. // See some discussion on the matter here: // http://google-opensource.blogspot.com/2013/01/c-containers-that-save-memory-and-time.html // Note, though, that this project is in no way related to the C++ B-Tree // implementation written about there. // // Within this tree, each node contains a slice of items and a (possibly nil) // slice of children. For basic numeric values or raw structs, this can cause // efficiency differences when compared to equivalent C++ template code that // stores values in arrays within the node: // * Due to the overhead of storing values as interfaces (each // value needs to be stored as the value itself, then 2 words for the // interface pointing to that value and its type), resulting in higher // memory use. // * Since interfaces can point to values anywhere in memory, values are // most likely not stored in contiguous blocks, resulting in a higher // number of cache misses. // These issues don't tend to matter, though, when working with strings or other // heap-allocated structures, since C++-equivalent structures also must store // pointers and also distribute their values across the heap. // // This implementation is designed to be a drop-in replacement to gollrb.LLRB // trees, (http://github.com/petar/gollrb), an excellent and probably the most // widely used ordered tree implementation in the Go ecosystem currently. // Its functions, therefore, exactly mirror those of // llrb.LLRB where possible. Unlike gollrb, though, we currently don't // support storing multiple equivalent values. package btree import ( "fmt" "io" "sort" "strings" "sync" ) // Item represents a single object in the tree. type Item interface { // Less tests whether the current item is less than the given argument. // // This must provide a strict weak ordering. // If !a.Less(b) && !b.Less(a), we treat this to mean a == b (i.e. we can only // hold one of either a or b in the tree). Less(than Item) bool } const ( DefaultFreeListSize = 32 ) var ( nilItems = make(items, 16) nilChildren = make(children, 16) ) // FreeList represents a free list of btree nodes. By default each // BTree has its own FreeList, but multiple BTrees can share the same // FreeList. // Two Btrees using the same freelist are safe for concurrent write access. type FreeList struct { mu sync.Mutex freelist []*node } // NewFreeList creates a new free list. // size is the maximum size of the returned free list. func NewFreeList(size int) *FreeList { return &FreeList{freelist: make([]*node, 0, size)} } func (f *FreeList) newNode() (n *node) { f.mu.Lock() index := len(f.freelist) - 1 if index < 0 { f.mu.Unlock() return new(node) } n = f.freelist[index] f.freelist[index] = nil f.freelist = f.freelist[:index] f.mu.Unlock() return } // freeNode adds the given node to the list, returning true if it was added // and false if it was discarded. func (f *FreeList) freeNode(n *node) (out bool) { f.mu.Lock() if len(f.freelist) < cap(f.freelist) { f.freelist = append(f.freelist, n) out = true } f.mu.Unlock() return } // ItemIterator allows callers of Ascend* to iterate in-order over portions of // the tree. When this function returns false, iteration will stop and the // associated Ascend* function will immediately return. type ItemIterator func(i Item) bool // New creates a new B-Tree with the given degree. // // New(2), for example, will create a 2-3-4 tree (each node contains 1-3 items // and 2-4 children). func New(degree int) *BTree { return NewWithFreeList(degree, NewFreeList(DefaultFreeListSize)) } // NewWithFreeList creates a new B-Tree that uses the given node free list. func NewWithFreeList(degree int, f *FreeList) *BTree { if degree <= 1 { panic("bad degree") } return &BTree{ degree: degree, cow: &copyOnWriteContext{freelist: f}, } } // items stores items in a node. type items []Item // insertAt inserts a value into the given index, pushing all subsequent values // forward. func (s *items) insertAt(index int, item Item) { *s = append(*s, nil) if index < len(*s) { copy((*s)[index+1:], (*s)[index:]) } (*s)[index] = item } // removeAt removes a value at a given index, pulling all subsequent values // back. func (s *items) removeAt(index int) Item { item := (*s)[index] copy((*s)[index:], (*s)[index+1:]) (*s)[len(*s)-1] = nil *s = (*s)[:len(*s)-1] return item } // pop removes and returns the last element in the list. func (s *items) pop() (out Item) { index := len(*s) - 1 out = (*s)[index] (*s)[index] = nil *s = (*s)[:index] return } // truncate truncates this instance at index so that it contains only the // first index items. index must be less than or equal to length. func (s *items) truncate(index int) { var toClear items *s, toClear = (*s)[:index], (*s)[index:] for len(toClear) > 0 { toClear = toClear[copy(toClear, nilItems):] } } // find returns the index where the given item should be inserted into this // list. 'found' is true if the item already exists in the list at the given // index. func (s items) find(item Item) (index int, found bool) { i := sort.Search(len(s), func(i int) bool { return item.Less(s[i]) }) if i > 0 && !s[i-1].Less(item) { return i - 1, true } return i, false } // children stores child nodes in a node. type children []*node // insertAt inserts a value into the given index, pushing all subsequent values // forward. func (s *children) insertAt(index int, n *node) { *s = append(*s, nil) if index < len(*s) { copy((*s)[index+1:], (*s)[index:]) } (*s)[index] = n } // removeAt removes a value at a given index, pulling all subsequent values // back. func (s *children) removeAt(index int) *node { n := (*s)[index] copy((*s)[index:], (*s)[index+1:]) (*s)[len(*s)-1] = nil *s = (*s)[:len(*s)-1] return n } // pop removes and returns the last element in the list. func (s *children) pop() (out *node) { index := len(*s) - 1 out = (*s)[index] (*s)[index] = nil *s = (*s)[:index] return } // truncate truncates this instance at index so that it contains only the // first index children. index must be less than or equal to length. func (s *children) truncate(index int) { var toClear children *s, toClear = (*s)[:index], (*s)[index:] for len(toClear) > 0 { toClear = toClear[copy(toClear, nilChildren):] } } // node is an internal node in a tree. // // It must at all times maintain the invariant that either // * len(children) == 0, len(items) unconstrained // * len(children) == len(items) + 1 type node struct { items items children children cow *copyOnWriteContext } func (n *node) mutableFor(cow *copyOnWriteContext) *node { if n.cow == cow { return n } out := cow.newNode() if cap(out.items) >= len(n.items) { out.items = out.items[:len(n.items)] } else { out.items = make(items, len(n.items), cap(n.items)) } copy(out.items, n.items) // Copy children if cap(out.children) >= len(n.children) { out.children = out.children[:len(n.children)] } else { out.children = make(children, len(n.children), cap(n.children)) } copy(out.children, n.children) return out } func (n *node) mutableChild(i int) *node { c := n.children[i].mutableFor(n.cow) n.children[i] = c return c } // split splits the given node at the given index. The current node shrinks, // and this function returns the item that existed at that index and a new node // containing all items/children after it. func (n *node) split(i int) (Item, *node) { item := n.items[i] next := n.cow.newNode() next.items = append(next.items, n.items[i+1:]...) n.items.truncate(i) if len(n.children) > 0 { next.children = append(next.children, n.children[i+1:]...) n.children.truncate(i + 1) } return item, next } // maybeSplitChild checks if a child should be split, and if so splits it. // Returns whether or not a split occurred. func (n *node) maybeSplitChild(i, maxItems int) bool { if len(n.children[i].items) < maxItems { return false } first := n.mutableChild(i) item, second := first.split(maxItems / 2) n.items.insertAt(i, item) n.children.insertAt(i+1, second) return true } // insert inserts an item into the subtree rooted at this node, making sure // no nodes in the subtree exceed maxItems items. Should an equivalent item be // be found/replaced by insert, it will be returned. func (n *node) insert(item Item, maxItems int) Item { i, found := n.items.find(item) if found { out := n.items[i] n.items[i] = item return out } if len(n.children) == 0 { n.items.insertAt(i, item) return nil } if n.maybeSplitChild(i, maxItems) { inTree := n.items[i] switch { case item.Less(inTree): // no change, we want first split node case inTree.Less(item): i++ // we want second split node default: out := n.items[i] n.items[i] = item return out } } return n.mutableChild(i).insert(item, maxItems) } // get finds the given key in the subtree and returns it. func (n *node) get(key Item) Item { i, found := n.items.find(key) if found { return n.items[i] } else if len(n.children) > 0 { return n.children[i].get(key) } return nil } // min returns the first item in the subtree. func min(n *node) Item { if n == nil { return nil } for len(n.children) > 0 { n = n.children[0] } if len(n.items) == 0 { return nil } return n.items[0] } // max returns the last item in the subtree. func max(n *node) Item { if n == nil { return nil } for len(n.children) > 0 { n = n.children[len(n.children)-1] } if len(n.items) == 0 { return nil } return n.items[len(n.items)-1] } // toRemove details what item to remove in a node.remove call. type toRemove int const ( removeItem toRemove = iota // removes the given item removeMin // removes smallest item in the subtree removeMax // removes largest item in the subtree ) // remove removes an item from the subtree rooted at this node. func (n *node) remove(item Item, minItems int, typ toRemove) Item { var i int var found bool switch typ { case removeMax: if len(n.children) == 0 { return n.items.pop() } i = len(n.items) case removeMin: if len(n.children) == 0 { return n.items.removeAt(0) } i = 0 case removeItem: i, found = n.items.find(item) if len(n.children) == 0 { if found { return n.items.removeAt(i) } return nil } default: panic("invalid type") } // If we get to here, we have children. if len(n.children[i].items) <= minItems { return n.growChildAndRemove(i, item, minItems, typ) } child := n.mutableChild(i) // Either we had enough items to begin with, or we've done some // merging/stealing, because we've got enough now and we're ready to return // stuff. if found { // The item exists at index 'i', and the child we've selected can give us a // predecessor, since if we've gotten here it's got > minItems items in it. out := n.items[i] // We use our special-case 'remove' call with typ=maxItem to pull the // predecessor of item i (the rightmost leaf of our immediate left child) // and set it into where we pulled the item from. n.items[i] = child.remove(nil, minItems, removeMax) return out } // Final recursive call. Once we're here, we know that the item isn't in this // node and that the child is big enough to remove from. return child.remove(item, minItems, typ) } // growChildAndRemove grows child 'i' to make sure it's possible to remove an // item from it while keeping it at minItems, then calls remove to actually // remove it. // // Most documentation says we have to do two sets of special casing: // 1) item is in this node // 2) item is in child // In both cases, we need to handle the two subcases: // A) node has enough values that it can spare one // B) node doesn't have enough values // For the latter, we have to check: // a) left sibling has node to spare // b) right sibling has node to spare // c) we must merge // To simplify our code here, we handle cases #1 and #2 the same: // If a node doesn't have enough items, we make sure it does (using a,b,c). // We then simply redo our remove call, and the second time (regardless of // whether we're in case 1 or 2), we'll have enough items and can guarantee // that we hit case A. func (n *node) growChildAndRemove(i int, item Item, minItems int, typ toRemove) Item { if i > 0 && len(n.children[i-1].items) > minItems { // Steal from left child child := n.mutableChild(i) stealFrom := n.mutableChild(i - 1) stolenItem := stealFrom.items.pop() child.items.insertAt(0, n.items[i-1]) n.items[i-1] = stolenItem if len(stealFrom.children) > 0 { child.children.insertAt(0, stealFrom.children.pop()) } } else if i < len(n.items) && len(n.children[i+1].items) > minItems { // steal from right child child := n.mutableChild(i) stealFrom := n.mutableChild(i + 1) stolenItem := stealFrom.items.removeAt(0) child.items = append(child.items, n.items[i]) n.items[i] = stolenItem if len(stealFrom.children) > 0 { child.children = append(child.children, stealFrom.children.removeAt(0)) } } else { if i >= len(n.items) { i-- } child := n.mutableChild(i) // merge with right child mergeItem := n.items.removeAt(i) mergeChild := n.children.removeAt(i + 1).mutableFor(n.cow) child.items = append(child.items, mergeItem) child.items = append(child.items, mergeChild.items...) child.children = append(child.children, mergeChild.children...) n.cow.freeNode(mergeChild) } return n.remove(item, minItems, typ) } type direction int const ( descend = direction(-1) ascend = direction(+1) ) // iterate provides a simple method for iterating over elements in the tree. // // When ascending, the 'start' should be less than 'stop' and when descending, // the 'start' should be greater than 'stop'. Setting 'includeStart' to true // will force the iterator to include the first item when it equals 'start', // thus creating a "greaterOrEqual" or "lessThanEqual" rather than just a // "greaterThan" or "lessThan" queries. func (n *node) iterate(dir direction, start, stop Item, includeStart bool, hit bool, iter ItemIterator) (bool, bool) { var ok, found bool var index int switch dir { case ascend: if start != nil { index, _ = n.items.find(start) } for i := index; i < len(n.items); i++ { if len(n.children) > 0 { if hit, ok = n.children[i].iterate(dir, start, stop, includeStart, hit, iter); !ok { return hit, false } } if !includeStart && !hit && start != nil && !start.Less(n.items[i]) { hit = true continue } hit = true if stop != nil && !n.items[i].Less(stop) { return hit, false } if !iter(n.items[i]) { return hit, false } } if len(n.children) > 0 { if hit, ok = n.children[len(n.children)-1].iterate(dir, start, stop, includeStart, hit, iter); !ok { return hit, false } } case descend: if start != nil { index, found = n.items.find(start) if !found { index = index - 1 } } else { index = len(n.items) - 1 } for i := index; i >= 0; i-- { if start != nil && !n.items[i].Less(start) { if !includeStart || hit || start.Less(n.items[i]) { continue } } if len(n.children) > 0 { if hit, ok = n.children[i+1].iterate(dir, start, stop, includeStart, hit, iter); !ok { return hit, false } } if stop != nil && !stop.Less(n.items[i]) { return hit, false // continue } hit = true if !iter(n.items[i]) { return hit, false } } if len(n.children) > 0 { if hit, ok = n.children[0].iterate(dir, start, stop, includeStart, hit, iter); !ok { return hit, false } } } return hit, true } // Used for testing/debugging purposes. func (n *node) print(w io.Writer, level int) { fmt.Fprintf(w, "%sNODE:%v\n", strings.Repeat(" ", level), n.items) for _, c := range n.children { c.print(w, level+1) } } // BTree is an implementation of a B-Tree. // // BTree stores Item instances in an ordered structure, allowing easy insertion, // removal, and iteration. // // Write operations are not safe for concurrent mutation by multiple // goroutines, but Read operations are. type BTree struct { degree int length int root *node cow *copyOnWriteContext } // copyOnWriteContext pointers determine node ownership... a tree with a write // context equivalent to a node's write context is allowed to modify that node. // A tree whose write context does not match a node's is not allowed to modify // it, and must create a new, writable copy (IE: it's a Clone). // // When doing any write operation, we maintain the invariant that the current // node's context is equal to the context of the tree that requested the write. // We do this by, before we descend into any node, creating a copy with the // correct context if the contexts don't match. // // Since the node we're currently visiting on any write has the requesting // tree's context, that node is modifiable in place. Children of that node may // not share context, but before we descend into them, we'll make a mutable // copy. type copyOnWriteContext struct { freelist *FreeList } // Clone clones the btree, lazily. Clone should not be called concurrently, // but the original tree (t) and the new tree (t2) can be used concurrently // once the Clone call completes. // // The internal tree structure of b is marked read-only and shared between t and // t2. Writes to both t and t2 use copy-on-write logic, creating new nodes // whenever one of b's original nodes would have been modified. Read operations // should have no performance degredation. Write operations for both t and t2 // will initially experience minor slow-downs caused by additional allocs and // copies due to the aforementioned copy-on-write logic, but should converge to // the original performance characteristics of the original tree. func (t *BTree) Clone() (t2 *BTree) { // Create two entirely new copy-on-write contexts. // This operation effectively creates three trees: // the original, shared nodes (old b.cow) // the new b.cow nodes // the new out.cow nodes cow1, cow2 := *t.cow, *t.cow out := *t t.cow = &cow1 out.cow = &cow2 return &out } // maxItems returns the max number of items to allow per node. func (t *BTree) maxItems() int { return t.degree*2 - 1 } // minItems returns the min number of items to allow per node (ignored for the // root node). func (t *BTree) minItems() int { return t.degree - 1 } func (c *copyOnWriteContext) newNode() (n *node) { n = c.freelist.newNode() n.cow = c return } type freeType int const ( ftFreelistFull freeType = iota // node was freed (available for GC, not stored in freelist) ftStored // node was stored in the freelist for later use ftNotOwned // node was ignored by COW, since it's owned by another one ) // freeNode frees a node within a given COW context, if it's owned by that // context. It returns what happened to the node (see freeType const // documentation). func (c *copyOnWriteContext) freeNode(n *node) freeType { if n.cow == c { // clear to allow GC n.items.truncate(0) n.children.truncate(0) n.cow = nil if c.freelist.freeNode(n) { return ftStored } else { return ftFreelistFull } } else { return ftNotOwned } } // ReplaceOrInsert adds the given item to the tree. If an item in the tree // already equals the given one, it is removed from the tree and returned. // Otherwise, nil is returned. // // nil cannot be added to the tree (will panic). func (t *BTree) ReplaceOrInsert(item Item) Item { if item == nil { panic("nil item being added to BTree") } if t.root == nil { t.root = t.cow.newNode() t.root.items = append(t.root.items, item) t.length++ return nil } else { t.root = t.root.mutableFor(t.cow) if len(t.root.items) >= t.maxItems() { item2, second := t.root.split(t.maxItems() / 2) oldroot := t.root t.root = t.cow.newNode() t.root.items = append(t.root.items, item2) t.root.children = append(t.root.children, oldroot, second) } } out := t.root.insert(item, t.maxItems()) if out == nil { t.length++ } return out } // Delete removes an item equal to the passed in item from the tree, returning // it. If no such item exists, returns nil. func (t *BTree) Delete(item Item) Item { return t.deleteItem(item, removeItem) } // DeleteMin removes the smallest item in the tree and returns it. // If no such item exists, returns nil. func (t *BTree) DeleteMin() Item { return t.deleteItem(nil, removeMin) } // DeleteMax removes the largest item in the tree and returns it. // If no such item exists, returns nil. func (t *BTree) DeleteMax() Item { return t.deleteItem(nil, removeMax) } func (t *BTree) deleteItem(item Item, typ toRemove) Item { if t.root == nil || len(t.root.items) == 0 { return nil } t.root = t.root.mutableFor(t.cow) out := t.root.remove(item, t.minItems(), typ) if len(t.root.items) == 0 && len(t.root.children) > 0 { oldroot := t.root t.root = t.root.children[0] t.cow.freeNode(oldroot) } if out != nil { t.length-- } return out } // AscendRange calls the iterator for every value in the tree within the range // [greaterOrEqual, lessThan), until iterator returns false. func (t *BTree) AscendRange(greaterOrEqual, lessThan Item, iterator ItemIterator) { if t.root == nil { return } t.root.iterate(ascend, greaterOrEqual, lessThan, true, false, iterator) } // AscendLessThan calls the iterator for every value in the tree within the range // [first, pivot), until iterator returns false. func (t *BTree) AscendLessThan(pivot Item, iterator ItemIterator) { if t.root == nil { return } t.root.iterate(ascend, nil, pivot, false, false, iterator) } // AscendGreaterOrEqual calls the iterator for every value in the tree within // the range [pivot, last], until iterator returns false. func (t *BTree) AscendGreaterOrEqual(pivot Item, iterator ItemIterator) { if t.root == nil { return } t.root.iterate(ascend, pivot, nil, true, false, iterator) } // Ascend calls the iterator for every value in the tree within the range // [first, last], until iterator returns false. func (t *BTree) Ascend(iterator ItemIterator) { if t.root == nil { return } t.root.iterate(ascend, nil, nil, false, false, iterator) } // DescendRange calls the iterator for every value in the tree within the range // [lessOrEqual, greaterThan), until iterator returns false. func (t *BTree) DescendRange(lessOrEqual, greaterThan Item, iterator ItemIterator) { if t.root == nil { return } t.root.iterate(descend, lessOrEqual, greaterThan, true, false, iterator) } // DescendLessOrEqual calls the iterator for every value in the tree within the range // [pivot, first], until iterator returns false. func (t *BTree) DescendLessOrEqual(pivot Item, iterator ItemIterator) { if t.root == nil { return } t.root.iterate(descend, pivot, nil, true, false, iterator) } // DescendGreaterThan calls the iterator for every value in the tree within // the range [last, pivot), until iterator returns false. func (t *BTree) DescendGreaterThan(pivot Item, iterator ItemIterator) { if t.root == nil { return } t.root.iterate(descend, nil, pivot, false, false, iterator) } // Descend calls the iterator for every value in the tree within the range // [last, first], until iterator returns false. func (t *BTree) Descend(iterator ItemIterator) { if t.root == nil { return } t.root.iterate(descend, nil, nil, false, false, iterator) } // Get looks for the key item in the tree, returning it. It returns nil if // unable to find that item. func (t *BTree) Get(key Item) Item { if t.root == nil { return nil } return t.root.get(key) } // Min returns the smallest item in the tree, or nil if the tree is empty. func (t *BTree) Min() Item { return min(t.root) } // Max returns the largest item in the tree, or nil if the tree is empty. func (t *BTree) Max() Item { return max(t.root) } // Has returns true if the given key is in the tree. func (t *BTree) Has(key Item) bool { return t.Get(key) != nil } // Len returns the number of items currently in the tree. func (t *BTree) Len() int { return t.length } // Clear removes all items from the btree. If addNodesToFreelist is true, // t's nodes are added to its freelist as part of this call, until the freelist // is full. Otherwise, the root node is simply dereferenced and the subtree // left to Go's normal GC processes. // // This can be much faster // than calling Delete on all elements, because that requires finding/removing // each element in the tree and updating the tree accordingly. It also is // somewhat faster than creating a new tree to replace the old one, because // nodes from the old tree are reclaimed into the freelist for use by the new // one, instead of being lost to the garbage collector. // // This call takes: // O(1): when addNodesToFreelist is false, this is a single operation. // O(1): when the freelist is already full, it breaks out immediately // O(freelist size): when the freelist is empty and the nodes are all owned // by this tree, nodes are added to the freelist until full. // O(tree size): when all nodes are owned by another tree, all nodes are // iterated over looking for nodes to add to the freelist, and due to // ownership, none are. func (t *BTree) Clear(addNodesToFreelist bool) { if t.root != nil && addNodesToFreelist { t.root.reset(t.cow) } t.root, t.length = nil, 0 } // reset returns a subtree to the freelist. It breaks out immediately if the // freelist is full, since the only benefit of iterating is to fill that // freelist up. Returns true if parent reset call should continue. func (n *node) reset(c *copyOnWriteContext) bool { for _, child := range n.children { if !child.reset(c) { return false } } return c.freeNode(n) != ftFreelistFull } // Int implements the Item interface for integers. type Int int // Less returns true if int(a) < int(b). func (a Int) Less(b Item) bool { return a < b.(Int) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/btree/btree_generic.go
vendor/github.com/google/btree/btree_generic.go
// Copyright 2014-2022 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //go:build go1.18 // +build go1.18 // In Go 1.18 and beyond, a BTreeG generic is created, and BTree is a specific // instantiation of that generic for the Item interface, with a backwards- // compatible API. Before go1.18, generics are not supported, // and BTree is just an implementation based around the Item interface. // Package btree implements in-memory B-Trees of arbitrary degree. // // btree implements an in-memory B-Tree for use as an ordered data structure. // It is not meant for persistent storage solutions. // // It has a flatter structure than an equivalent red-black or other binary tree, // which in some cases yields better memory usage and/or performance. // See some discussion on the matter here: // http://google-opensource.blogspot.com/2013/01/c-containers-that-save-memory-and-time.html // Note, though, that this project is in no way related to the C++ B-Tree // implementation written about there. // // Within this tree, each node contains a slice of items and a (possibly nil) // slice of children. For basic numeric values or raw structs, this can cause // efficiency differences when compared to equivalent C++ template code that // stores values in arrays within the node: // * Due to the overhead of storing values as interfaces (each // value needs to be stored as the value itself, then 2 words for the // interface pointing to that value and its type), resulting in higher // memory use. // * Since interfaces can point to values anywhere in memory, values are // most likely not stored in contiguous blocks, resulting in a higher // number of cache misses. // These issues don't tend to matter, though, when working with strings or other // heap-allocated structures, since C++-equivalent structures also must store // pointers and also distribute their values across the heap. // // This implementation is designed to be a drop-in replacement to gollrb.LLRB // trees, (http://github.com/petar/gollrb), an excellent and probably the most // widely used ordered tree implementation in the Go ecosystem currently. // Its functions, therefore, exactly mirror those of // llrb.LLRB where possible. Unlike gollrb, though, we currently don't // support storing multiple equivalent values. // // There are two implementations; those suffixed with 'G' are generics, usable // for any type, and require a passed-in "less" function to define their ordering. // Those without this prefix are specific to the 'Item' interface, and use // its 'Less' function for ordering. package btree import ( "fmt" "io" "sort" "strings" "sync" ) // Item represents a single object in the tree. type Item interface { // Less tests whether the current item is less than the given argument. // // This must provide a strict weak ordering. // If !a.Less(b) && !b.Less(a), we treat this to mean a == b (i.e. we can only // hold one of either a or b in the tree). Less(than Item) bool } const ( DefaultFreeListSize = 32 ) // FreeListG represents a free list of btree nodes. By default each // BTree has its own FreeList, but multiple BTrees can share the same // FreeList, in particular when they're created with Clone. // Two Btrees using the same freelist are safe for concurrent write access. type FreeListG[T any] struct { mu sync.Mutex freelist []*node[T] } // NewFreeListG creates a new free list. // size is the maximum size of the returned free list. func NewFreeListG[T any](size int) *FreeListG[T] { return &FreeListG[T]{freelist: make([]*node[T], 0, size)} } func (f *FreeListG[T]) newNode() (n *node[T]) { f.mu.Lock() index := len(f.freelist) - 1 if index < 0 { f.mu.Unlock() return new(node[T]) } n = f.freelist[index] f.freelist[index] = nil f.freelist = f.freelist[:index] f.mu.Unlock() return } func (f *FreeListG[T]) freeNode(n *node[T]) (out bool) { f.mu.Lock() if len(f.freelist) < cap(f.freelist) { f.freelist = append(f.freelist, n) out = true } f.mu.Unlock() return } // ItemIteratorG allows callers of {A/De}scend* to iterate in-order over portions of // the tree. When this function returns false, iteration will stop and the // associated Ascend* function will immediately return. type ItemIteratorG[T any] func(item T) bool // Ordered represents the set of types for which the '<' operator work. type Ordered interface { ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64 | ~string } // Less[T] returns a default LessFunc that uses the '<' operator for types that support it. func Less[T Ordered]() LessFunc[T] { return func(a, b T) bool { return a < b } } // NewOrderedG creates a new B-Tree for ordered types. func NewOrderedG[T Ordered](degree int) *BTreeG[T] { return NewG[T](degree, Less[T]()) } // NewG creates a new B-Tree with the given degree. // // NewG(2), for example, will create a 2-3-4 tree (each node contains 1-3 items // and 2-4 children). // // The passed-in LessFunc determines how objects of type T are ordered. func NewG[T any](degree int, less LessFunc[T]) *BTreeG[T] { return NewWithFreeListG(degree, less, NewFreeListG[T](DefaultFreeListSize)) } // NewWithFreeListG creates a new B-Tree that uses the given node free list. func NewWithFreeListG[T any](degree int, less LessFunc[T], f *FreeListG[T]) *BTreeG[T] { if degree <= 1 { panic("bad degree") } return &BTreeG[T]{ degree: degree, cow: &copyOnWriteContext[T]{freelist: f, less: less}, } } // items stores items in a node. type items[T any] []T // insertAt inserts a value into the given index, pushing all subsequent values // forward. func (s *items[T]) insertAt(index int, item T) { var zero T *s = append(*s, zero) if index < len(*s) { copy((*s)[index+1:], (*s)[index:]) } (*s)[index] = item } // removeAt removes a value at a given index, pulling all subsequent values // back. func (s *items[T]) removeAt(index int) T { item := (*s)[index] copy((*s)[index:], (*s)[index+1:]) var zero T (*s)[len(*s)-1] = zero *s = (*s)[:len(*s)-1] return item } // pop removes and returns the last element in the list. func (s *items[T]) pop() (out T) { index := len(*s) - 1 out = (*s)[index] var zero T (*s)[index] = zero *s = (*s)[:index] return } // truncate truncates this instance at index so that it contains only the // first index items. index must be less than or equal to length. func (s *items[T]) truncate(index int) { var toClear items[T] *s, toClear = (*s)[:index], (*s)[index:] var zero T for i := 0; i < len(toClear); i++ { toClear[i] = zero } } // find returns the index where the given item should be inserted into this // list. 'found' is true if the item already exists in the list at the given // index. func (s items[T]) find(item T, less func(T, T) bool) (index int, found bool) { i := sort.Search(len(s), func(i int) bool { return less(item, s[i]) }) if i > 0 && !less(s[i-1], item) { return i - 1, true } return i, false } // node is an internal node in a tree. // // It must at all times maintain the invariant that either // * len(children) == 0, len(items) unconstrained // * len(children) == len(items) + 1 type node[T any] struct { items items[T] children items[*node[T]] cow *copyOnWriteContext[T] } func (n *node[T]) mutableFor(cow *copyOnWriteContext[T]) *node[T] { if n.cow == cow { return n } out := cow.newNode() if cap(out.items) >= len(n.items) { out.items = out.items[:len(n.items)] } else { out.items = make(items[T], len(n.items), cap(n.items)) } copy(out.items, n.items) // Copy children if cap(out.children) >= len(n.children) { out.children = out.children[:len(n.children)] } else { out.children = make(items[*node[T]], len(n.children), cap(n.children)) } copy(out.children, n.children) return out } func (n *node[T]) mutableChild(i int) *node[T] { c := n.children[i].mutableFor(n.cow) n.children[i] = c return c } // split splits the given node at the given index. The current node shrinks, // and this function returns the item that existed at that index and a new node // containing all items/children after it. func (n *node[T]) split(i int) (T, *node[T]) { item := n.items[i] next := n.cow.newNode() next.items = append(next.items, n.items[i+1:]...) n.items.truncate(i) if len(n.children) > 0 { next.children = append(next.children, n.children[i+1:]...) n.children.truncate(i + 1) } return item, next } // maybeSplitChild checks if a child should be split, and if so splits it. // Returns whether or not a split occurred. func (n *node[T]) maybeSplitChild(i, maxItems int) bool { if len(n.children[i].items) < maxItems { return false } first := n.mutableChild(i) item, second := first.split(maxItems / 2) n.items.insertAt(i, item) n.children.insertAt(i+1, second) return true } // insert inserts an item into the subtree rooted at this node, making sure // no nodes in the subtree exceed maxItems items. Should an equivalent item be // be found/replaced by insert, it will be returned. func (n *node[T]) insert(item T, maxItems int) (_ T, _ bool) { i, found := n.items.find(item, n.cow.less) if found { out := n.items[i] n.items[i] = item return out, true } if len(n.children) == 0 { n.items.insertAt(i, item) return } if n.maybeSplitChild(i, maxItems) { inTree := n.items[i] switch { case n.cow.less(item, inTree): // no change, we want first split node case n.cow.less(inTree, item): i++ // we want second split node default: out := n.items[i] n.items[i] = item return out, true } } return n.mutableChild(i).insert(item, maxItems) } // get finds the given key in the subtree and returns it. func (n *node[T]) get(key T) (_ T, _ bool) { i, found := n.items.find(key, n.cow.less) if found { return n.items[i], true } else if len(n.children) > 0 { return n.children[i].get(key) } return } // min returns the first item in the subtree. func min[T any](n *node[T]) (_ T, found bool) { if n == nil { return } for len(n.children) > 0 { n = n.children[0] } if len(n.items) == 0 { return } return n.items[0], true } // max returns the last item in the subtree. func max[T any](n *node[T]) (_ T, found bool) { if n == nil { return } for len(n.children) > 0 { n = n.children[len(n.children)-1] } if len(n.items) == 0 { return } return n.items[len(n.items)-1], true } // toRemove details what item to remove in a node.remove call. type toRemove int const ( removeItem toRemove = iota // removes the given item removeMin // removes smallest item in the subtree removeMax // removes largest item in the subtree ) // remove removes an item from the subtree rooted at this node. func (n *node[T]) remove(item T, minItems int, typ toRemove) (_ T, _ bool) { var i int var found bool switch typ { case removeMax: if len(n.children) == 0 { return n.items.pop(), true } i = len(n.items) case removeMin: if len(n.children) == 0 { return n.items.removeAt(0), true } i = 0 case removeItem: i, found = n.items.find(item, n.cow.less) if len(n.children) == 0 { if found { return n.items.removeAt(i), true } return } default: panic("invalid type") } // If we get to here, we have children. if len(n.children[i].items) <= minItems { return n.growChildAndRemove(i, item, minItems, typ) } child := n.mutableChild(i) // Either we had enough items to begin with, or we've done some // merging/stealing, because we've got enough now and we're ready to return // stuff. if found { // The item exists at index 'i', and the child we've selected can give us a // predecessor, since if we've gotten here it's got > minItems items in it. out := n.items[i] // We use our special-case 'remove' call with typ=maxItem to pull the // predecessor of item i (the rightmost leaf of our immediate left child) // and set it into where we pulled the item from. var zero T n.items[i], _ = child.remove(zero, minItems, removeMax) return out, true } // Final recursive call. Once we're here, we know that the item isn't in this // node and that the child is big enough to remove from. return child.remove(item, minItems, typ) } // growChildAndRemove grows child 'i' to make sure it's possible to remove an // item from it while keeping it at minItems, then calls remove to actually // remove it. // // Most documentation says we have to do two sets of special casing: // 1) item is in this node // 2) item is in child // In both cases, we need to handle the two subcases: // A) node has enough values that it can spare one // B) node doesn't have enough values // For the latter, we have to check: // a) left sibling has node to spare // b) right sibling has node to spare // c) we must merge // To simplify our code here, we handle cases #1 and #2 the same: // If a node doesn't have enough items, we make sure it does (using a,b,c). // We then simply redo our remove call, and the second time (regardless of // whether we're in case 1 or 2), we'll have enough items and can guarantee // that we hit case A. func (n *node[T]) growChildAndRemove(i int, item T, minItems int, typ toRemove) (T, bool) { if i > 0 && len(n.children[i-1].items) > minItems { // Steal from left child child := n.mutableChild(i) stealFrom := n.mutableChild(i - 1) stolenItem := stealFrom.items.pop() child.items.insertAt(0, n.items[i-1]) n.items[i-1] = stolenItem if len(stealFrom.children) > 0 { child.children.insertAt(0, stealFrom.children.pop()) } } else if i < len(n.items) && len(n.children[i+1].items) > minItems { // steal from right child child := n.mutableChild(i) stealFrom := n.mutableChild(i + 1) stolenItem := stealFrom.items.removeAt(0) child.items = append(child.items, n.items[i]) n.items[i] = stolenItem if len(stealFrom.children) > 0 { child.children = append(child.children, stealFrom.children.removeAt(0)) } } else { if i >= len(n.items) { i-- } child := n.mutableChild(i) // merge with right child mergeItem := n.items.removeAt(i) mergeChild := n.children.removeAt(i + 1) child.items = append(child.items, mergeItem) child.items = append(child.items, mergeChild.items...) child.children = append(child.children, mergeChild.children...) n.cow.freeNode(mergeChild) } return n.remove(item, minItems, typ) } type direction int const ( descend = direction(-1) ascend = direction(+1) ) type optionalItem[T any] struct { item T valid bool } func optional[T any](item T) optionalItem[T] { return optionalItem[T]{item: item, valid: true} } func empty[T any]() optionalItem[T] { return optionalItem[T]{} } // iterate provides a simple method for iterating over elements in the tree. // // When ascending, the 'start' should be less than 'stop' and when descending, // the 'start' should be greater than 'stop'. Setting 'includeStart' to true // will force the iterator to include the first item when it equals 'start', // thus creating a "greaterOrEqual" or "lessThanEqual" rather than just a // "greaterThan" or "lessThan" queries. func (n *node[T]) iterate(dir direction, start, stop optionalItem[T], includeStart bool, hit bool, iter ItemIteratorG[T]) (bool, bool) { var ok, found bool var index int switch dir { case ascend: if start.valid { index, _ = n.items.find(start.item, n.cow.less) } for i := index; i < len(n.items); i++ { if len(n.children) > 0 { if hit, ok = n.children[i].iterate(dir, start, stop, includeStart, hit, iter); !ok { return hit, false } } if !includeStart && !hit && start.valid && !n.cow.less(start.item, n.items[i]) { hit = true continue } hit = true if stop.valid && !n.cow.less(n.items[i], stop.item) { return hit, false } if !iter(n.items[i]) { return hit, false } } if len(n.children) > 0 { if hit, ok = n.children[len(n.children)-1].iterate(dir, start, stop, includeStart, hit, iter); !ok { return hit, false } } case descend: if start.valid { index, found = n.items.find(start.item, n.cow.less) if !found { index = index - 1 } } else { index = len(n.items) - 1 } for i := index; i >= 0; i-- { if start.valid && !n.cow.less(n.items[i], start.item) { if !includeStart || hit || n.cow.less(start.item, n.items[i]) { continue } } if len(n.children) > 0 { if hit, ok = n.children[i+1].iterate(dir, start, stop, includeStart, hit, iter); !ok { return hit, false } } if stop.valid && !n.cow.less(stop.item, n.items[i]) { return hit, false // continue } hit = true if !iter(n.items[i]) { return hit, false } } if len(n.children) > 0 { if hit, ok = n.children[0].iterate(dir, start, stop, includeStart, hit, iter); !ok { return hit, false } } } return hit, true } // print is used for testing/debugging purposes. func (n *node[T]) print(w io.Writer, level int) { fmt.Fprintf(w, "%sNODE:%v\n", strings.Repeat(" ", level), n.items) for _, c := range n.children { c.print(w, level+1) } } // BTreeG is a generic implementation of a B-Tree. // // BTreeG stores items of type T in an ordered structure, allowing easy insertion, // removal, and iteration. // // Write operations are not safe for concurrent mutation by multiple // goroutines, but Read operations are. type BTreeG[T any] struct { degree int length int root *node[T] cow *copyOnWriteContext[T] } // LessFunc[T] determines how to order a type 'T'. It should implement a strict // ordering, and should return true if within that ordering, 'a' < 'b'. type LessFunc[T any] func(a, b T) bool // copyOnWriteContext pointers determine node ownership... a tree with a write // context equivalent to a node's write context is allowed to modify that node. // A tree whose write context does not match a node's is not allowed to modify // it, and must create a new, writable copy (IE: it's a Clone). // // When doing any write operation, we maintain the invariant that the current // node's context is equal to the context of the tree that requested the write. // We do this by, before we descend into any node, creating a copy with the // correct context if the contexts don't match. // // Since the node we're currently visiting on any write has the requesting // tree's context, that node is modifiable in place. Children of that node may // not share context, but before we descend into them, we'll make a mutable // copy. type copyOnWriteContext[T any] struct { freelist *FreeListG[T] less LessFunc[T] } // Clone clones the btree, lazily. Clone should not be called concurrently, // but the original tree (t) and the new tree (t2) can be used concurrently // once the Clone call completes. // // The internal tree structure of b is marked read-only and shared between t and // t2. Writes to both t and t2 use copy-on-write logic, creating new nodes // whenever one of b's original nodes would have been modified. Read operations // should have no performance degredation. Write operations for both t and t2 // will initially experience minor slow-downs caused by additional allocs and // copies due to the aforementioned copy-on-write logic, but should converge to // the original performance characteristics of the original tree. func (t *BTreeG[T]) Clone() (t2 *BTreeG[T]) { // Create two entirely new copy-on-write contexts. // This operation effectively creates three trees: // the original, shared nodes (old b.cow) // the new b.cow nodes // the new out.cow nodes cow1, cow2 := *t.cow, *t.cow out := *t t.cow = &cow1 out.cow = &cow2 return &out } // maxItems returns the max number of items to allow per node. func (t *BTreeG[T]) maxItems() int { return t.degree*2 - 1 } // minItems returns the min number of items to allow per node (ignored for the // root node). func (t *BTreeG[T]) minItems() int { return t.degree - 1 } func (c *copyOnWriteContext[T]) newNode() (n *node[T]) { n = c.freelist.newNode() n.cow = c return } type freeType int const ( ftFreelistFull freeType = iota // node was freed (available for GC, not stored in freelist) ftStored // node was stored in the freelist for later use ftNotOwned // node was ignored by COW, since it's owned by another one ) // freeNode frees a node within a given COW context, if it's owned by that // context. It returns what happened to the node (see freeType const // documentation). func (c *copyOnWriteContext[T]) freeNode(n *node[T]) freeType { if n.cow == c { // clear to allow GC n.items.truncate(0) n.children.truncate(0) n.cow = nil if c.freelist.freeNode(n) { return ftStored } else { return ftFreelistFull } } else { return ftNotOwned } } // ReplaceOrInsert adds the given item to the tree. If an item in the tree // already equals the given one, it is removed from the tree and returned, // and the second return value is true. Otherwise, (zeroValue, false) // // nil cannot be added to the tree (will panic). func (t *BTreeG[T]) ReplaceOrInsert(item T) (_ T, _ bool) { if t.root == nil { t.root = t.cow.newNode() t.root.items = append(t.root.items, item) t.length++ return } else { t.root = t.root.mutableFor(t.cow) if len(t.root.items) >= t.maxItems() { item2, second := t.root.split(t.maxItems() / 2) oldroot := t.root t.root = t.cow.newNode() t.root.items = append(t.root.items, item2) t.root.children = append(t.root.children, oldroot, second) } } out, outb := t.root.insert(item, t.maxItems()) if !outb { t.length++ } return out, outb } // Delete removes an item equal to the passed in item from the tree, returning // it. If no such item exists, returns (zeroValue, false). func (t *BTreeG[T]) Delete(item T) (T, bool) { return t.deleteItem(item, removeItem) } // DeleteMin removes the smallest item in the tree and returns it. // If no such item exists, returns (zeroValue, false). func (t *BTreeG[T]) DeleteMin() (T, bool) { var zero T return t.deleteItem(zero, removeMin) } // DeleteMax removes the largest item in the tree and returns it. // If no such item exists, returns (zeroValue, false). func (t *BTreeG[T]) DeleteMax() (T, bool) { var zero T return t.deleteItem(zero, removeMax) } func (t *BTreeG[T]) deleteItem(item T, typ toRemove) (_ T, _ bool) { if t.root == nil || len(t.root.items) == 0 { return } t.root = t.root.mutableFor(t.cow) out, outb := t.root.remove(item, t.minItems(), typ) if len(t.root.items) == 0 && len(t.root.children) > 0 { oldroot := t.root t.root = t.root.children[0] t.cow.freeNode(oldroot) } if outb { t.length-- } return out, outb } // AscendRange calls the iterator for every value in the tree within the range // [greaterOrEqual, lessThan), until iterator returns false. func (t *BTreeG[T]) AscendRange(greaterOrEqual, lessThan T, iterator ItemIteratorG[T]) { if t.root == nil { return } t.root.iterate(ascend, optional[T](greaterOrEqual), optional[T](lessThan), true, false, iterator) } // AscendLessThan calls the iterator for every value in the tree within the range // [first, pivot), until iterator returns false. func (t *BTreeG[T]) AscendLessThan(pivot T, iterator ItemIteratorG[T]) { if t.root == nil { return } t.root.iterate(ascend, empty[T](), optional(pivot), false, false, iterator) } // AscendGreaterOrEqual calls the iterator for every value in the tree within // the range [pivot, last], until iterator returns false. func (t *BTreeG[T]) AscendGreaterOrEqual(pivot T, iterator ItemIteratorG[T]) { if t.root == nil { return } t.root.iterate(ascend, optional[T](pivot), empty[T](), true, false, iterator) } // Ascend calls the iterator for every value in the tree within the range // [first, last], until iterator returns false. func (t *BTreeG[T]) Ascend(iterator ItemIteratorG[T]) { if t.root == nil { return } t.root.iterate(ascend, empty[T](), empty[T](), false, false, iterator) } // DescendRange calls the iterator for every value in the tree within the range // [lessOrEqual, greaterThan), until iterator returns false. func (t *BTreeG[T]) DescendRange(lessOrEqual, greaterThan T, iterator ItemIteratorG[T]) { if t.root == nil { return } t.root.iterate(descend, optional[T](lessOrEqual), optional[T](greaterThan), true, false, iterator) } // DescendLessOrEqual calls the iterator for every value in the tree within the range // [pivot, first], until iterator returns false. func (t *BTreeG[T]) DescendLessOrEqual(pivot T, iterator ItemIteratorG[T]) { if t.root == nil { return } t.root.iterate(descend, optional[T](pivot), empty[T](), true, false, iterator) } // DescendGreaterThan calls the iterator for every value in the tree within // the range [last, pivot), until iterator returns false. func (t *BTreeG[T]) DescendGreaterThan(pivot T, iterator ItemIteratorG[T]) { if t.root == nil { return } t.root.iterate(descend, empty[T](), optional[T](pivot), false, false, iterator) } // Descend calls the iterator for every value in the tree within the range // [last, first], until iterator returns false. func (t *BTreeG[T]) Descend(iterator ItemIteratorG[T]) { if t.root == nil { return } t.root.iterate(descend, empty[T](), empty[T](), false, false, iterator) } // Get looks for the key item in the tree, returning it. It returns // (zeroValue, false) if unable to find that item. func (t *BTreeG[T]) Get(key T) (_ T, _ bool) { if t.root == nil { return } return t.root.get(key) } // Min returns the smallest item in the tree, or (zeroValue, false) if the tree is empty. func (t *BTreeG[T]) Min() (_ T, _ bool) { return min(t.root) } // Max returns the largest item in the tree, or (zeroValue, false) if the tree is empty. func (t *BTreeG[T]) Max() (_ T, _ bool) { return max(t.root) } // Has returns true if the given key is in the tree. func (t *BTreeG[T]) Has(key T) bool { _, ok := t.Get(key) return ok } // Len returns the number of items currently in the tree. func (t *BTreeG[T]) Len() int { return t.length } // Clear removes all items from the btree. If addNodesToFreelist is true, // t's nodes are added to its freelist as part of this call, until the freelist // is full. Otherwise, the root node is simply dereferenced and the subtree // left to Go's normal GC processes. // // This can be much faster // than calling Delete on all elements, because that requires finding/removing // each element in the tree and updating the tree accordingly. It also is // somewhat faster than creating a new tree to replace the old one, because // nodes from the old tree are reclaimed into the freelist for use by the new // one, instead of being lost to the garbage collector. // // This call takes: // O(1): when addNodesToFreelist is false, this is a single operation. // O(1): when the freelist is already full, it breaks out immediately // O(freelist size): when the freelist is empty and the nodes are all owned // by this tree, nodes are added to the freelist until full. // O(tree size): when all nodes are owned by another tree, all nodes are // iterated over looking for nodes to add to the freelist, and due to // ownership, none are. func (t *BTreeG[T]) Clear(addNodesToFreelist bool) { if t.root != nil && addNodesToFreelist { t.root.reset(t.cow) } t.root, t.length = nil, 0 } // reset returns a subtree to the freelist. It breaks out immediately if the // freelist is full, since the only benefit of iterating is to fill that // freelist up. Returns true if parent reset call should continue. func (n *node[T]) reset(c *copyOnWriteContext[T]) bool { for _, child := range n.children { if !child.reset(c) { return false } } return c.freeNode(n) != ftFreelistFull } // Int implements the Item interface for integers. type Int int // Less returns true if int(a) < int(b). func (a Int) Less(b Item) bool { return a < b.(Int) } // BTree is an implementation of a B-Tree. // // BTree stores Item instances in an ordered structure, allowing easy insertion, // removal, and iteration. // // Write operations are not safe for concurrent mutation by multiple // goroutines, but Read operations are. type BTree BTreeG[Item] var itemLess LessFunc[Item] = func(a, b Item) bool { return a.Less(b) } // New creates a new B-Tree with the given degree. // // New(2), for example, will create a 2-3-4 tree (each node contains 1-3 items // and 2-4 children). func New(degree int) *BTree { return (*BTree)(NewG[Item](degree, itemLess)) } // FreeList represents a free list of btree nodes. By default each // BTree has its own FreeList, but multiple BTrees can share the same // FreeList. // Two Btrees using the same freelist are safe for concurrent write access. type FreeList FreeListG[Item] // NewFreeList creates a new free list. // size is the maximum size of the returned free list. func NewFreeList(size int) *FreeList { return (*FreeList)(NewFreeListG[Item](size)) } // NewWithFreeList creates a new B-Tree that uses the given node free list. func NewWithFreeList(degree int, f *FreeList) *BTree { return (*BTree)(NewWithFreeListG[Item](degree, itemLess, (*FreeListG[Item])(f))) } // ItemIterator allows callers of Ascend* to iterate in-order over portions of // the tree. When this function returns false, iteration will stop and the // associated Ascend* function will immediately return. type ItemIterator ItemIteratorG[Item] // Clone clones the btree, lazily. Clone should not be called concurrently, // but the original tree (t) and the new tree (t2) can be used concurrently // once the Clone call completes. // // The internal tree structure of b is marked read-only and shared between t and // t2. Writes to both t and t2 use copy-on-write logic, creating new nodes // whenever one of b's original nodes would have been modified. Read operations // should have no performance degredation. Write operations for both t and t2 // will initially experience minor slow-downs caused by additional allocs and // copies due to the aforementioned copy-on-write logic, but should converge to // the original performance characteristics of the original tree. func (t *BTree) Clone() (t2 *BTree) { return (*BTree)((*BTreeG[Item])(t).Clone()) } // Delete removes an item equal to the passed in item from the tree, returning // it. If no such item exists, returns nil. func (t *BTree) Delete(item Item) Item { i, _ := (*BTreeG[Item])(t).Delete(item) return i } // DeleteMax removes the largest item in the tree and returns it. // If no such item exists, returns nil. func (t *BTree) DeleteMax() Item { i, _ := (*BTreeG[Item])(t).DeleteMax() return i } // DeleteMin removes the smallest item in the tree and returns it. // If no such item exists, returns nil. func (t *BTree) DeleteMin() Item { i, _ := (*BTreeG[Item])(t).DeleteMin() return i } // Get looks for the key item in the tree, returning it. It returns nil if // unable to find that item. func (t *BTree) Get(key Item) Item { i, _ := (*BTreeG[Item])(t).Get(key) return i } // Max returns the largest item in the tree, or nil if the tree is empty. func (t *BTree) Max() Item { i, _ := (*BTreeG[Item])(t).Max() return i } // Min returns the smallest item in the tree, or nil if the tree is empty. func (t *BTree) Min() Item { i, _ := (*BTreeG[Item])(t).Min() return i } // Has returns true if the given key is in the tree. func (t *BTree) Has(key Item) bool { return (*BTreeG[Item])(t).Has(key) } // ReplaceOrInsert adds the given item to the tree. If an item in the tree // already equals the given one, it is removed from the tree and returned. // Otherwise, nil is returned. // // nil cannot be added to the tree (will panic). func (t *BTree) ReplaceOrInsert(item Item) Item { i, _ := (*BTreeG[Item])(t).ReplaceOrInsert(item) return i } // AscendRange calls the iterator for every value in the tree within the range // [greaterOrEqual, lessThan), until iterator returns false. func (t *BTree) AscendRange(greaterOrEqual, lessThan Item, iterator ItemIterator) { (*BTreeG[Item])(t).AscendRange(greaterOrEqual, lessThan, (ItemIteratorG[Item])(iterator)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/go-cmp/cmp/report_references.go
vendor/github.com/google/go-cmp/cmp/report_references.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 cmp import ( "fmt" "reflect" "strings" "github.com/google/go-cmp/cmp/internal/flags" "github.com/google/go-cmp/cmp/internal/value" ) const ( pointerDelimPrefix = "⟪" pointerDelimSuffix = "⟫" ) // formatPointer prints the address of the pointer. func formatPointer(p value.Pointer, withDelims bool) string { v := p.Uintptr() if flags.Deterministic { v = 0xdeadf00f // Only used for stable testing purposes } if withDelims { return pointerDelimPrefix + formatHex(uint64(v)) + pointerDelimSuffix } return formatHex(uint64(v)) } // pointerReferences is a stack of pointers visited so far. type pointerReferences [][2]value.Pointer func (ps *pointerReferences) PushPair(vx, vy reflect.Value, d diffMode, deref bool) (pp [2]value.Pointer) { if deref && vx.IsValid() { vx = vx.Addr() } if deref && vy.IsValid() { vy = vy.Addr() } switch d { case diffUnknown, diffIdentical: pp = [2]value.Pointer{value.PointerOf(vx), value.PointerOf(vy)} case diffRemoved: pp = [2]value.Pointer{value.PointerOf(vx), value.Pointer{}} case diffInserted: pp = [2]value.Pointer{value.Pointer{}, value.PointerOf(vy)} } *ps = append(*ps, pp) return pp } func (ps *pointerReferences) Push(v reflect.Value) (p value.Pointer, seen bool) { p = value.PointerOf(v) for _, pp := range *ps { if p == pp[0] || p == pp[1] { return p, true } } *ps = append(*ps, [2]value.Pointer{p, p}) return p, false } func (ps *pointerReferences) Pop() { *ps = (*ps)[:len(*ps)-1] } // trunkReferences is metadata for a textNode indicating that the sub-tree // represents the value for either pointer in a pair of references. type trunkReferences struct{ pp [2]value.Pointer } // trunkReference is metadata for a textNode indicating that the sub-tree // represents the value for the given pointer reference. type trunkReference struct{ p value.Pointer } // leafReference is metadata for a textNode indicating that the value is // truncated as it refers to another part of the tree (i.e., a trunk). type leafReference struct{ p value.Pointer } func wrapTrunkReferences(pp [2]value.Pointer, s textNode) textNode { switch { case pp[0].IsNil(): return &textWrap{Value: s, Metadata: trunkReference{pp[1]}} case pp[1].IsNil(): return &textWrap{Value: s, Metadata: trunkReference{pp[0]}} case pp[0] == pp[1]: return &textWrap{Value: s, Metadata: trunkReference{pp[0]}} default: return &textWrap{Value: s, Metadata: trunkReferences{pp}} } } func wrapTrunkReference(p value.Pointer, printAddress bool, s textNode) textNode { var prefix string if printAddress { prefix = formatPointer(p, true) } return &textWrap{Prefix: prefix, Value: s, Metadata: trunkReference{p}} } func makeLeafReference(p value.Pointer, printAddress bool) textNode { out := &textWrap{Prefix: "(", Value: textEllipsis, Suffix: ")"} var prefix string if printAddress { prefix = formatPointer(p, true) } return &textWrap{Prefix: prefix, Value: out, Metadata: leafReference{p}} } // resolveReferences walks the textNode tree searching for any leaf reference // metadata and resolves each against the corresponding trunk references. // Since pointer addresses in memory are not particularly readable to the user, // it replaces each pointer value with an arbitrary and unique reference ID. func resolveReferences(s textNode) { var walkNodes func(textNode, func(textNode)) walkNodes = func(s textNode, f func(textNode)) { f(s) switch s := s.(type) { case *textWrap: walkNodes(s.Value, f) case textList: for _, r := range s { walkNodes(r.Value, f) } } } // Collect all trunks and leaves with reference metadata. var trunks, leaves []*textWrap walkNodes(s, func(s textNode) { if s, ok := s.(*textWrap); ok { switch s.Metadata.(type) { case leafReference: leaves = append(leaves, s) case trunkReference, trunkReferences: trunks = append(trunks, s) } } }) // No leaf references to resolve. if len(leaves) == 0 { return } // Collect the set of all leaf references to resolve. leafPtrs := make(map[value.Pointer]bool) for _, leaf := range leaves { leafPtrs[leaf.Metadata.(leafReference).p] = true } // Collect the set of trunk pointers that are always paired together. // This allows us to assign a single ID to both pointers for brevity. // If a pointer in a pair ever occurs by itself or as a different pair, // then the pair is broken. pairedTrunkPtrs := make(map[value.Pointer]value.Pointer) unpair := func(p value.Pointer) { if !pairedTrunkPtrs[p].IsNil() { pairedTrunkPtrs[pairedTrunkPtrs[p]] = value.Pointer{} // invalidate other half } pairedTrunkPtrs[p] = value.Pointer{} // invalidate this half } for _, trunk := range trunks { switch p := trunk.Metadata.(type) { case trunkReference: unpair(p.p) // standalone pointer cannot be part of a pair case trunkReferences: p0, ok0 := pairedTrunkPtrs[p.pp[0]] p1, ok1 := pairedTrunkPtrs[p.pp[1]] switch { case !ok0 && !ok1: // Register the newly seen pair. pairedTrunkPtrs[p.pp[0]] = p.pp[1] pairedTrunkPtrs[p.pp[1]] = p.pp[0] case ok0 && ok1 && p0 == p.pp[1] && p1 == p.pp[0]: // Exact pair already seen; do nothing. default: // Pair conflicts with some other pair; break all pairs. unpair(p.pp[0]) unpair(p.pp[1]) } } } // Correlate each pointer referenced by leaves to a unique identifier, // and print the IDs for each trunk that matches those pointers. var nextID uint ptrIDs := make(map[value.Pointer]uint) newID := func() uint { id := nextID nextID++ return id } for _, trunk := range trunks { switch p := trunk.Metadata.(type) { case trunkReference: if print := leafPtrs[p.p]; print { id, ok := ptrIDs[p.p] if !ok { id = newID() ptrIDs[p.p] = id } trunk.Prefix = updateReferencePrefix(trunk.Prefix, formatReference(id)) } case trunkReferences: print0 := leafPtrs[p.pp[0]] print1 := leafPtrs[p.pp[1]] if print0 || print1 { id0, ok0 := ptrIDs[p.pp[0]] id1, ok1 := ptrIDs[p.pp[1]] isPair := pairedTrunkPtrs[p.pp[0]] == p.pp[1] && pairedTrunkPtrs[p.pp[1]] == p.pp[0] if isPair { var id uint assert(ok0 == ok1) // must be seen together or not at all if ok0 { assert(id0 == id1) // must have the same ID id = id0 } else { id = newID() ptrIDs[p.pp[0]] = id ptrIDs[p.pp[1]] = id } trunk.Prefix = updateReferencePrefix(trunk.Prefix, formatReference(id)) } else { if print0 && !ok0 { id0 = newID() ptrIDs[p.pp[0]] = id0 } if print1 && !ok1 { id1 = newID() ptrIDs[p.pp[1]] = id1 } switch { case print0 && print1: trunk.Prefix = updateReferencePrefix(trunk.Prefix, formatReference(id0)+","+formatReference(id1)) case print0: trunk.Prefix = updateReferencePrefix(trunk.Prefix, formatReference(id0)) case print1: trunk.Prefix = updateReferencePrefix(trunk.Prefix, formatReference(id1)) } } } } } // Update all leaf references with the unique identifier. for _, leaf := range leaves { if id, ok := ptrIDs[leaf.Metadata.(leafReference).p]; ok { leaf.Prefix = updateReferencePrefix(leaf.Prefix, formatReference(id)) } } } func formatReference(id uint) string { return fmt.Sprintf("ref#%d", id) } func updateReferencePrefix(prefix, ref string) string { if prefix == "" { return pointerDelimPrefix + ref + pointerDelimSuffix } suffix := strings.TrimPrefix(prefix, pointerDelimPrefix) return pointerDelimPrefix + ref + ": " + suffix }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/go-cmp/cmp/report_compare.go
vendor/github.com/google/go-cmp/cmp/report_compare.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 cmp import ( "fmt" "reflect" ) // numContextRecords is the number of surrounding equal records to print. const numContextRecords = 2 type diffMode byte const ( diffUnknown diffMode = 0 diffIdentical diffMode = ' ' diffRemoved diffMode = '-' diffInserted diffMode = '+' ) type typeMode int const ( // emitType always prints the type. emitType typeMode = iota // elideType never prints the type. elideType // autoType prints the type only for composite kinds // (i.e., structs, slices, arrays, and maps). autoType ) type formatOptions struct { // DiffMode controls the output mode of FormatDiff. // // If diffUnknown, then produce a diff of the x and y values. // If diffIdentical, then emit values as if they were equal. // If diffRemoved, then only emit x values (ignoring y values). // If diffInserted, then only emit y values (ignoring x values). DiffMode diffMode // TypeMode controls whether to print the type for the current node. // // As a general rule of thumb, we always print the type of the next node // after an interface, and always elide the type of the next node after // a slice or map node. TypeMode typeMode // formatValueOptions are options specific to printing reflect.Values. formatValueOptions } func (opts formatOptions) WithDiffMode(d diffMode) formatOptions { opts.DiffMode = d return opts } func (opts formatOptions) WithTypeMode(t typeMode) formatOptions { opts.TypeMode = t return opts } func (opts formatOptions) WithVerbosity(level int) formatOptions { opts.VerbosityLevel = level opts.LimitVerbosity = true return opts } func (opts formatOptions) verbosity() uint { switch { case opts.VerbosityLevel < 0: return 0 case opts.VerbosityLevel > 16: return 16 // some reasonable maximum to avoid shift overflow default: return uint(opts.VerbosityLevel) } } const maxVerbosityPreset = 6 // verbosityPreset modifies the verbosity settings given an index // between 0 and maxVerbosityPreset, inclusive. func verbosityPreset(opts formatOptions, i int) formatOptions { opts.VerbosityLevel = int(opts.verbosity()) + 2*i if i > 0 { opts.AvoidStringer = true } if i >= maxVerbosityPreset { opts.PrintAddresses = true opts.QualifiedNames = true } return opts } // FormatDiff converts a valueNode tree into a textNode tree, where the later // is a textual representation of the differences detected in the former. func (opts formatOptions) FormatDiff(v *valueNode, ptrs *pointerReferences) (out textNode) { if opts.DiffMode == diffIdentical { opts = opts.WithVerbosity(1) } else if opts.verbosity() < 3 { opts = opts.WithVerbosity(3) } // Check whether we have specialized formatting for this node. // This is not necessary, but helpful for producing more readable outputs. if opts.CanFormatDiffSlice(v) { return opts.FormatDiffSlice(v) } var parentKind reflect.Kind if v.parent != nil && v.parent.TransformerName == "" { parentKind = v.parent.Type.Kind() } // For leaf nodes, format the value based on the reflect.Values alone. // As a special case, treat equal []byte as a leaf nodes. isBytes := v.Type.Kind() == reflect.Slice && v.Type.Elem() == byteType isEqualBytes := isBytes && v.NumDiff+v.NumIgnored+v.NumTransformed == 0 if v.MaxDepth == 0 || isEqualBytes { switch opts.DiffMode { case diffUnknown, diffIdentical: // Format Equal. if v.NumDiff == 0 { outx := opts.FormatValue(v.ValueX, parentKind, ptrs) outy := opts.FormatValue(v.ValueY, parentKind, ptrs) if v.NumIgnored > 0 && v.NumSame == 0 { return textEllipsis } else if outx.Len() < outy.Len() { return outx } else { return outy } } // Format unequal. assert(opts.DiffMode == diffUnknown) var list textList outx := opts.WithTypeMode(elideType).FormatValue(v.ValueX, parentKind, ptrs) outy := opts.WithTypeMode(elideType).FormatValue(v.ValueY, parentKind, ptrs) for i := 0; i <= maxVerbosityPreset && outx != nil && outy != nil && outx.Equal(outy); i++ { opts2 := verbosityPreset(opts, i).WithTypeMode(elideType) outx = opts2.FormatValue(v.ValueX, parentKind, ptrs) outy = opts2.FormatValue(v.ValueY, parentKind, ptrs) } if outx != nil { list = append(list, textRecord{Diff: '-', Value: outx}) } if outy != nil { list = append(list, textRecord{Diff: '+', Value: outy}) } return opts.WithTypeMode(emitType).FormatType(v.Type, list) case diffRemoved: return opts.FormatValue(v.ValueX, parentKind, ptrs) case diffInserted: return opts.FormatValue(v.ValueY, parentKind, ptrs) default: panic("invalid diff mode") } } // Register slice element to support cycle detection. if parentKind == reflect.Slice { ptrRefs := ptrs.PushPair(v.ValueX, v.ValueY, opts.DiffMode, true) defer ptrs.Pop() defer func() { out = wrapTrunkReferences(ptrRefs, out) }() } // Descend into the child value node. if v.TransformerName != "" { out := opts.WithTypeMode(emitType).FormatDiff(v.Value, ptrs) out = &textWrap{Prefix: "Inverse(" + v.TransformerName + ", ", Value: out, Suffix: ")"} return opts.FormatType(v.Type, out) } else { switch k := v.Type.Kind(); k { case reflect.Struct, reflect.Array, reflect.Slice: out = opts.formatDiffList(v.Records, k, ptrs) out = opts.FormatType(v.Type, out) case reflect.Map: // Register map to support cycle detection. ptrRefs := ptrs.PushPair(v.ValueX, v.ValueY, opts.DiffMode, false) defer ptrs.Pop() out = opts.formatDiffList(v.Records, k, ptrs) out = wrapTrunkReferences(ptrRefs, out) out = opts.FormatType(v.Type, out) case reflect.Ptr: // Register pointer to support cycle detection. ptrRefs := ptrs.PushPair(v.ValueX, v.ValueY, opts.DiffMode, false) defer ptrs.Pop() out = opts.FormatDiff(v.Value, ptrs) out = wrapTrunkReferences(ptrRefs, out) out = &textWrap{Prefix: "&", Value: out} case reflect.Interface: out = opts.WithTypeMode(emitType).FormatDiff(v.Value, ptrs) default: panic(fmt.Sprintf("%v cannot have children", k)) } return out } } func (opts formatOptions) formatDiffList(recs []reportRecord, k reflect.Kind, ptrs *pointerReferences) textNode { // Derive record name based on the data structure kind. var name string var formatKey func(reflect.Value) string switch k { case reflect.Struct: name = "field" opts = opts.WithTypeMode(autoType) formatKey = func(v reflect.Value) string { return v.String() } case reflect.Slice, reflect.Array: name = "element" opts = opts.WithTypeMode(elideType) formatKey = func(reflect.Value) string { return "" } case reflect.Map: name = "entry" opts = opts.WithTypeMode(elideType) formatKey = func(v reflect.Value) string { return formatMapKey(v, false, ptrs) } } maxLen := -1 if opts.LimitVerbosity { if opts.DiffMode == diffIdentical { maxLen = ((1 << opts.verbosity()) >> 1) << 2 // 0, 4, 8, 16, 32, etc... } else { maxLen = (1 << opts.verbosity()) << 1 // 2, 4, 8, 16, 32, 64, etc... } opts.VerbosityLevel-- } // Handle unification. switch opts.DiffMode { case diffIdentical, diffRemoved, diffInserted: var list textList var deferredEllipsis bool // Add final "..." to indicate records were dropped for _, r := range recs { if len(list) == maxLen { deferredEllipsis = true break } // Elide struct fields that are zero value. if k == reflect.Struct { var isZero bool switch opts.DiffMode { case diffIdentical: isZero = r.Value.ValueX.IsZero() || r.Value.ValueY.IsZero() case diffRemoved: isZero = r.Value.ValueX.IsZero() case diffInserted: isZero = r.Value.ValueY.IsZero() } if isZero { continue } } // Elide ignored nodes. if r.Value.NumIgnored > 0 && r.Value.NumSame+r.Value.NumDiff == 0 { deferredEllipsis = !(k == reflect.Slice || k == reflect.Array) if !deferredEllipsis { list.AppendEllipsis(diffStats{}) } continue } if out := opts.FormatDiff(r.Value, ptrs); out != nil { list = append(list, textRecord{Key: formatKey(r.Key), Value: out}) } } if deferredEllipsis { list.AppendEllipsis(diffStats{}) } return &textWrap{Prefix: "{", Value: list, Suffix: "}"} case diffUnknown: default: panic("invalid diff mode") } // Handle differencing. var numDiffs int var list textList var keys []reflect.Value // invariant: len(list) == len(keys) groups := coalesceAdjacentRecords(name, recs) maxGroup := diffStats{Name: name} for i, ds := range groups { if maxLen >= 0 && numDiffs >= maxLen { maxGroup = maxGroup.Append(ds) continue } // Handle equal records. if ds.NumDiff() == 0 { // Compute the number of leading and trailing records to print. var numLo, numHi int numEqual := ds.NumIgnored + ds.NumIdentical for numLo < numContextRecords && numLo+numHi < numEqual && i != 0 { if r := recs[numLo].Value; r.NumIgnored > 0 && r.NumSame+r.NumDiff == 0 { break } numLo++ } for numHi < numContextRecords && numLo+numHi < numEqual && i != len(groups)-1 { if r := recs[numEqual-numHi-1].Value; r.NumIgnored > 0 && r.NumSame+r.NumDiff == 0 { break } numHi++ } if numEqual-(numLo+numHi) == 1 && ds.NumIgnored == 0 { numHi++ // Avoid pointless coalescing of a single equal record } // Format the equal values. for _, r := range recs[:numLo] { out := opts.WithDiffMode(diffIdentical).FormatDiff(r.Value, ptrs) list = append(list, textRecord{Key: formatKey(r.Key), Value: out}) keys = append(keys, r.Key) } if numEqual > numLo+numHi { ds.NumIdentical -= numLo + numHi list.AppendEllipsis(ds) for len(keys) < len(list) { keys = append(keys, reflect.Value{}) } } for _, r := range recs[numEqual-numHi : numEqual] { out := opts.WithDiffMode(diffIdentical).FormatDiff(r.Value, ptrs) list = append(list, textRecord{Key: formatKey(r.Key), Value: out}) keys = append(keys, r.Key) } recs = recs[numEqual:] continue } // Handle unequal records. for _, r := range recs[:ds.NumDiff()] { switch { case opts.CanFormatDiffSlice(r.Value): out := opts.FormatDiffSlice(r.Value) list = append(list, textRecord{Key: formatKey(r.Key), Value: out}) keys = append(keys, r.Key) case r.Value.NumChildren == r.Value.MaxDepth: outx := opts.WithDiffMode(diffRemoved).FormatDiff(r.Value, ptrs) outy := opts.WithDiffMode(diffInserted).FormatDiff(r.Value, ptrs) for i := 0; i <= maxVerbosityPreset && outx != nil && outy != nil && outx.Equal(outy); i++ { opts2 := verbosityPreset(opts, i) outx = opts2.WithDiffMode(diffRemoved).FormatDiff(r.Value, ptrs) outy = opts2.WithDiffMode(diffInserted).FormatDiff(r.Value, ptrs) } if outx != nil { list = append(list, textRecord{Diff: diffRemoved, Key: formatKey(r.Key), Value: outx}) keys = append(keys, r.Key) } if outy != nil { list = append(list, textRecord{Diff: diffInserted, Key: formatKey(r.Key), Value: outy}) keys = append(keys, r.Key) } default: out := opts.FormatDiff(r.Value, ptrs) list = append(list, textRecord{Key: formatKey(r.Key), Value: out}) keys = append(keys, r.Key) } } recs = recs[ds.NumDiff():] numDiffs += ds.NumDiff() } if maxGroup.IsZero() { assert(len(recs) == 0) } else { list.AppendEllipsis(maxGroup) for len(keys) < len(list) { keys = append(keys, reflect.Value{}) } } assert(len(list) == len(keys)) // For maps, the default formatting logic uses fmt.Stringer which may // produce ambiguous output. Avoid calling String to disambiguate. if k == reflect.Map { var ambiguous bool seenKeys := map[string]reflect.Value{} for i, currKey := range keys { if currKey.IsValid() { strKey := list[i].Key prevKey, seen := seenKeys[strKey] if seen && prevKey.CanInterface() && currKey.CanInterface() { ambiguous = prevKey.Interface() != currKey.Interface() if ambiguous { break } } seenKeys[strKey] = currKey } } if ambiguous { for i, k := range keys { if k.IsValid() { list[i].Key = formatMapKey(k, true, ptrs) } } } } return &textWrap{Prefix: "{", Value: list, Suffix: "}"} } // coalesceAdjacentRecords coalesces the list of records into groups of // adjacent equal, or unequal counts. func coalesceAdjacentRecords(name string, recs []reportRecord) (groups []diffStats) { var prevCase int // Arbitrary index into which case last occurred lastStats := func(i int) *diffStats { if prevCase != i { groups = append(groups, diffStats{Name: name}) prevCase = i } return &groups[len(groups)-1] } for _, r := range recs { switch rv := r.Value; { case rv.NumIgnored > 0 && rv.NumSame+rv.NumDiff == 0: lastStats(1).NumIgnored++ case rv.NumDiff == 0: lastStats(1).NumIdentical++ case rv.NumDiff > 0 && !rv.ValueY.IsValid(): lastStats(2).NumRemoved++ case rv.NumDiff > 0 && !rv.ValueX.IsValid(): lastStats(2).NumInserted++ default: lastStats(2).NumModified++ } } return groups }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/go-cmp/cmp/report_reflect.go
vendor/github.com/google/go-cmp/cmp/report_reflect.go
// Copyright 2019, The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package cmp import ( "bytes" "fmt" "reflect" "strconv" "strings" "unicode" "unicode/utf8" "github.com/google/go-cmp/cmp/internal/value" ) var ( anyType = reflect.TypeOf((*interface{})(nil)).Elem() stringType = reflect.TypeOf((*string)(nil)).Elem() bytesType = reflect.TypeOf((*[]byte)(nil)).Elem() byteType = reflect.TypeOf((*byte)(nil)).Elem() ) type formatValueOptions struct { // AvoidStringer controls whether to avoid calling custom stringer // methods like error.Error or fmt.Stringer.String. AvoidStringer bool // PrintAddresses controls whether to print the address of all pointers, // slice elements, and maps. PrintAddresses bool // QualifiedNames controls whether FormatType uses the fully qualified name // (including the full package path as opposed to just the package name). QualifiedNames bool // VerbosityLevel controls the amount of output to produce. // A higher value produces more output. A value of zero or lower produces // no output (represented using an ellipsis). // If LimitVerbosity is false, then the level is treated as infinite. VerbosityLevel int // LimitVerbosity specifies that formatting should respect VerbosityLevel. LimitVerbosity bool } // FormatType prints the type as if it were wrapping s. // This may return s as-is depending on the current type and TypeMode mode. func (opts formatOptions) FormatType(t reflect.Type, s textNode) textNode { // Check whether to emit the type or not. switch opts.TypeMode { case autoType: switch t.Kind() { case reflect.Struct, reflect.Slice, reflect.Array, reflect.Map: if s.Equal(textNil) { return s } default: return s } if opts.DiffMode == diffIdentical { return s // elide type for identical nodes } case elideType: return s } // Determine the type label, applying special handling for unnamed types. typeName := value.TypeString(t, opts.QualifiedNames) if t.Name() == "" { // According to Go grammar, certain type literals contain symbols that // do not strongly bind to the next lexicographical token (e.g., *T). switch t.Kind() { case reflect.Chan, reflect.Func, reflect.Ptr: typeName = "(" + typeName + ")" } } return &textWrap{Prefix: typeName, Value: wrapParens(s)} } // wrapParens wraps s with a set of parenthesis, but avoids it if the // wrapped node itself is already surrounded by a pair of parenthesis or braces. // It handles unwrapping one level of pointer-reference nodes. func wrapParens(s textNode) textNode { var refNode *textWrap if s2, ok := s.(*textWrap); ok { // Unwrap a single pointer reference node. switch s2.Metadata.(type) { case leafReference, trunkReference, trunkReferences: refNode = s2 if s3, ok := refNode.Value.(*textWrap); ok { s2 = s3 } } // Already has delimiters that make parenthesis unnecessary. hasParens := strings.HasPrefix(s2.Prefix, "(") && strings.HasSuffix(s2.Suffix, ")") hasBraces := strings.HasPrefix(s2.Prefix, "{") && strings.HasSuffix(s2.Suffix, "}") if hasParens || hasBraces { return s } } if refNode != nil { refNode.Value = &textWrap{Prefix: "(", Value: refNode.Value, Suffix: ")"} return s } return &textWrap{Prefix: "(", Value: s, Suffix: ")"} } // FormatValue prints the reflect.Value, taking extra care to avoid descending // into pointers already in ptrs. As pointers are visited, ptrs is also updated. func (opts formatOptions) FormatValue(v reflect.Value, parentKind reflect.Kind, ptrs *pointerReferences) (out textNode) { if !v.IsValid() { return nil } t := v.Type() // Check slice element for cycles. if parentKind == reflect.Slice { ptrRef, visited := ptrs.Push(v.Addr()) if visited { return makeLeafReference(ptrRef, false) } defer ptrs.Pop() defer func() { out = wrapTrunkReference(ptrRef, false, out) }() } // Check whether there is an Error or String method to call. if !opts.AvoidStringer && v.CanInterface() { // Avoid calling Error or String methods on nil receivers since many // implementations crash when doing so. if (t.Kind() != reflect.Ptr && t.Kind() != reflect.Interface) || !v.IsNil() { var prefix, strVal string func() { // Swallow and ignore any panics from String or Error. defer func() { recover() }() switch v := v.Interface().(type) { case error: strVal = v.Error() prefix = "e" case fmt.Stringer: strVal = v.String() prefix = "s" } }() if prefix != "" { return opts.formatString(prefix, strVal) } } } // Check whether to explicitly wrap the result with the type. var skipType bool defer func() { if !skipType { out = opts.FormatType(t, out) } }() switch t.Kind() { case reflect.Bool: return textLine(fmt.Sprint(v.Bool())) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return textLine(fmt.Sprint(v.Int())) case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64: return textLine(fmt.Sprint(v.Uint())) case reflect.Uint8: if parentKind == reflect.Slice || parentKind == reflect.Array { return textLine(formatHex(v.Uint())) } return textLine(fmt.Sprint(v.Uint())) case reflect.Uintptr: return textLine(formatHex(v.Uint())) case reflect.Float32, reflect.Float64: return textLine(fmt.Sprint(v.Float())) case reflect.Complex64, reflect.Complex128: return textLine(fmt.Sprint(v.Complex())) case reflect.String: return opts.formatString("", v.String()) case reflect.UnsafePointer, reflect.Chan, reflect.Func: return textLine(formatPointer(value.PointerOf(v), true)) case reflect.Struct: var list textList v := makeAddressable(v) // needed for retrieveUnexportedField maxLen := v.NumField() if opts.LimitVerbosity { maxLen = ((1 << opts.verbosity()) >> 1) << 2 // 0, 4, 8, 16, 32, etc... opts.VerbosityLevel-- } for i := 0; i < v.NumField(); i++ { vv := v.Field(i) if vv.IsZero() { continue // Elide fields with zero values } if len(list) == maxLen { list.AppendEllipsis(diffStats{}) break } sf := t.Field(i) if !isExported(sf.Name) { vv = retrieveUnexportedField(v, sf, true) } s := opts.WithTypeMode(autoType).FormatValue(vv, t.Kind(), ptrs) list = append(list, textRecord{Key: sf.Name, Value: s}) } return &textWrap{Prefix: "{", Value: list, Suffix: "}"} case reflect.Slice: if v.IsNil() { return textNil } // Check whether this is a []byte of text data. if t.Elem() == byteType { b := v.Bytes() isPrintSpace := func(r rune) bool { return unicode.IsPrint(r) || unicode.IsSpace(r) } if len(b) > 0 && utf8.Valid(b) && len(bytes.TrimFunc(b, isPrintSpace)) == 0 { out = opts.formatString("", string(b)) skipType = true return opts.FormatType(t, out) } } fallthrough case reflect.Array: maxLen := v.Len() if opts.LimitVerbosity { maxLen = ((1 << opts.verbosity()) >> 1) << 2 // 0, 4, 8, 16, 32, etc... opts.VerbosityLevel-- } var list textList for i := 0; i < v.Len(); i++ { if len(list) == maxLen { list.AppendEllipsis(diffStats{}) break } s := opts.WithTypeMode(elideType).FormatValue(v.Index(i), t.Kind(), ptrs) list = append(list, textRecord{Value: s}) } out = &textWrap{Prefix: "{", Value: list, Suffix: "}"} if t.Kind() == reflect.Slice && opts.PrintAddresses { header := fmt.Sprintf("ptr:%v, len:%d, cap:%d", formatPointer(value.PointerOf(v), false), v.Len(), v.Cap()) out = &textWrap{Prefix: pointerDelimPrefix + header + pointerDelimSuffix, Value: out} } return out case reflect.Map: if v.IsNil() { return textNil } // Check pointer for cycles. ptrRef, visited := ptrs.Push(v) if visited { return makeLeafReference(ptrRef, opts.PrintAddresses) } defer ptrs.Pop() maxLen := v.Len() if opts.LimitVerbosity { maxLen = ((1 << opts.verbosity()) >> 1) << 2 // 0, 4, 8, 16, 32, etc... opts.VerbosityLevel-- } var list textList for _, k := range value.SortKeys(v.MapKeys()) { if len(list) == maxLen { list.AppendEllipsis(diffStats{}) break } sk := formatMapKey(k, false, ptrs) sv := opts.WithTypeMode(elideType).FormatValue(v.MapIndex(k), t.Kind(), ptrs) list = append(list, textRecord{Key: sk, Value: sv}) } out = &textWrap{Prefix: "{", Value: list, Suffix: "}"} out = wrapTrunkReference(ptrRef, opts.PrintAddresses, out) return out case reflect.Ptr: if v.IsNil() { return textNil } // Check pointer for cycles. ptrRef, visited := ptrs.Push(v) if visited { out = makeLeafReference(ptrRef, opts.PrintAddresses) return &textWrap{Prefix: "&", Value: out} } defer ptrs.Pop() // Skip the name only if this is an unnamed pointer type. // Otherwise taking the address of a value does not reproduce // the named pointer type. if v.Type().Name() == "" { skipType = true // Let the underlying value print the type instead } out = opts.FormatValue(v.Elem(), t.Kind(), ptrs) out = wrapTrunkReference(ptrRef, opts.PrintAddresses, out) out = &textWrap{Prefix: "&", Value: out} return out case reflect.Interface: if v.IsNil() { return textNil } // Interfaces accept different concrete types, // so configure the underlying value to explicitly print the type. return opts.WithTypeMode(emitType).FormatValue(v.Elem(), t.Kind(), ptrs) default: panic(fmt.Sprintf("%v kind not handled", v.Kind())) } } func (opts formatOptions) formatString(prefix, s string) textNode { maxLen := len(s) maxLines := strings.Count(s, "\n") + 1 if opts.LimitVerbosity { maxLen = (1 << opts.verbosity()) << 5 // 32, 64, 128, 256, etc... maxLines = (1 << opts.verbosity()) << 2 // 4, 8, 16, 32, 64, etc... } // For multiline strings, use the triple-quote syntax, // but only use it when printing removed or inserted nodes since // we only want the extra verbosity for those cases. lines := strings.Split(strings.TrimSuffix(s, "\n"), "\n") isTripleQuoted := len(lines) >= 4 && (opts.DiffMode == '-' || opts.DiffMode == '+') for i := 0; i < len(lines) && isTripleQuoted; i++ { lines[i] = strings.TrimPrefix(strings.TrimSuffix(lines[i], "\r"), "\r") // trim leading/trailing carriage returns for legacy Windows endline support isPrintable := func(r rune) bool { return unicode.IsPrint(r) || r == '\t' // specially treat tab as printable } line := lines[i] isTripleQuoted = !strings.HasPrefix(strings.TrimPrefix(line, prefix), `"""`) && !strings.HasPrefix(line, "...") && strings.TrimFunc(line, isPrintable) == "" && len(line) <= maxLen } if isTripleQuoted { var list textList list = append(list, textRecord{Diff: opts.DiffMode, Value: textLine(prefix + `"""`), ElideComma: true}) for i, line := range lines { if numElided := len(lines) - i; i == maxLines-1 && numElided > 1 { comment := commentString(fmt.Sprintf("%d elided lines", numElided)) list = append(list, textRecord{Diff: opts.DiffMode, Value: textEllipsis, ElideComma: true, Comment: comment}) break } list = append(list, textRecord{Diff: opts.DiffMode, Value: textLine(line), ElideComma: true}) } list = append(list, textRecord{Diff: opts.DiffMode, Value: textLine(prefix + `"""`), ElideComma: true}) return &textWrap{Prefix: "(", Value: list, Suffix: ")"} } // Format the string as a single-line quoted string. if len(s) > maxLen+len(textEllipsis) { return textLine(prefix + formatString(s[:maxLen]) + string(textEllipsis)) } return textLine(prefix + formatString(s)) } // formatMapKey formats v as if it were a map key. // The result is guaranteed to be a single line. func formatMapKey(v reflect.Value, disambiguate bool, ptrs *pointerReferences) string { var opts formatOptions opts.DiffMode = diffIdentical opts.TypeMode = elideType opts.PrintAddresses = disambiguate opts.AvoidStringer = disambiguate opts.QualifiedNames = disambiguate opts.VerbosityLevel = maxVerbosityPreset opts.LimitVerbosity = true s := opts.FormatValue(v, reflect.Map, ptrs).String() return strings.TrimSpace(s) } // formatString prints s as a double-quoted or backtick-quoted string. func formatString(s string) string { // Use quoted string if it the same length as a raw string literal. // Otherwise, attempt to use the raw string form. qs := strconv.Quote(s) if len(qs) == 1+len(s)+1 { return qs } // Disallow newlines to ensure output is a single line. // Only allow printable runes for readability purposes. rawInvalid := func(r rune) bool { return r == '`' || r == '\n' || !(unicode.IsPrint(r) || r == '\t') } if utf8.ValidString(s) && strings.IndexFunc(s, rawInvalid) < 0 { return "`" + s + "`" } return qs } // formatHex prints u as a hexadecimal integer in Go notation. func formatHex(u uint64) string { var f string switch { case u <= 0xff: f = "0x%02x" case u <= 0xffff: f = "0x%04x" case u <= 0xffffff: f = "0x%06x" case u <= 0xffffffff: f = "0x%08x" case u <= 0xffffffffff: f = "0x%010x" case u <= 0xffffffffffff: f = "0x%012x" case u <= 0xffffffffffffff: f = "0x%014x" case u <= 0xffffffffffffffff: f = "0x%016x" } return fmt.Sprintf(f, u) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/go-cmp/cmp/path.go
vendor/github.com/google/go-cmp/cmp/path.go
// Copyright 2017, 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 cmp import ( "fmt" "reflect" "strings" "unicode" "unicode/utf8" "github.com/google/go-cmp/cmp/internal/value" ) // Path is a list of [PathStep] describing the sequence of operations to get // from some root type to the current position in the value tree. // The first Path element is always an operation-less [PathStep] that exists // simply to identify the initial type. // // When traversing structs with embedded structs, the embedded struct will // always be accessed as a field before traversing the fields of the // embedded struct themselves. That is, an exported field from the // embedded struct will never be accessed directly from the parent struct. type Path []PathStep // PathStep is a union-type for specific operations to traverse // a value's tree structure. Users of this package never need to implement // these types as values of this type will be returned by this package. // // Implementations of this interface: // - [StructField] // - [SliceIndex] // - [MapIndex] // - [Indirect] // - [TypeAssertion] // - [Transform] type PathStep interface { String() string // Type is the resulting type after performing the path step. Type() reflect.Type // Values is the resulting values after performing the path step. // The type of each valid value is guaranteed to be identical to Type. // // In some cases, one or both may be invalid or have restrictions: // - For StructField, both are not interface-able if the current field // is unexported and the struct type is not explicitly permitted by // an Exporter to traverse unexported fields. // - For SliceIndex, one may be invalid if an element is missing from // either the x or y slice. // - For MapIndex, one may be invalid if an entry is missing from // either the x or y map. // // The provided values must not be mutated. Values() (vx, vy reflect.Value) } var ( _ PathStep = StructField{} _ PathStep = SliceIndex{} _ PathStep = MapIndex{} _ PathStep = Indirect{} _ PathStep = TypeAssertion{} _ PathStep = Transform{} ) func (pa *Path) push(s PathStep) { *pa = append(*pa, s) } func (pa *Path) pop() { *pa = (*pa)[:len(*pa)-1] } // Last returns the last [PathStep] in the Path. // If the path is empty, this returns a non-nil [PathStep] // that reports a nil [PathStep.Type]. func (pa Path) Last() PathStep { return pa.Index(-1) } // Index returns the ith step in the Path and supports negative indexing. // A negative index starts counting from the tail of the Path such that -1 // refers to the last step, -2 refers to the second-to-last step, and so on. // If index is invalid, this returns a non-nil [PathStep] // that reports a nil [PathStep.Type]. func (pa Path) Index(i int) PathStep { if i < 0 { i = len(pa) + i } if i < 0 || i >= len(pa) { return pathStep{} } return pa[i] } // String returns the simplified path to a node. // The simplified path only contains struct field accesses. // // For example: // // MyMap.MySlices.MyField func (pa Path) String() string { var ss []string for _, s := range pa { if _, ok := s.(StructField); ok { ss = append(ss, s.String()) } } return strings.TrimPrefix(strings.Join(ss, ""), ".") } // GoString returns the path to a specific node using Go syntax. // // For example: // // (*root.MyMap["key"].(*mypkg.MyStruct).MySlices)[2][3].MyField func (pa Path) GoString() string { var ssPre, ssPost []string var numIndirect int for i, s := range pa { var nextStep PathStep if i+1 < len(pa) { nextStep = pa[i+1] } switch s := s.(type) { case Indirect: numIndirect++ pPre, pPost := "(", ")" switch nextStep.(type) { case Indirect: continue // Next step is indirection, so let them batch up case StructField: numIndirect-- // Automatic indirection on struct fields case nil: pPre, pPost = "", "" // Last step; no need for parenthesis } if numIndirect > 0 { ssPre = append(ssPre, pPre+strings.Repeat("*", numIndirect)) ssPost = append(ssPost, pPost) } numIndirect = 0 continue case Transform: ssPre = append(ssPre, s.trans.name+"(") ssPost = append(ssPost, ")") continue } ssPost = append(ssPost, s.String()) } for i, j := 0, len(ssPre)-1; i < j; i, j = i+1, j-1 { ssPre[i], ssPre[j] = ssPre[j], ssPre[i] } return strings.Join(ssPre, "") + strings.Join(ssPost, "") } type pathStep struct { typ reflect.Type vx, vy reflect.Value } func (ps pathStep) Type() reflect.Type { return ps.typ } func (ps pathStep) Values() (vx, vy reflect.Value) { return ps.vx, ps.vy } func (ps pathStep) String() string { if ps.typ == nil { return "<nil>" } s := value.TypeString(ps.typ, false) if s == "" || strings.ContainsAny(s, "{}\n") { return "root" // Type too simple or complex to print } return fmt.Sprintf("{%s}", s) } // StructField is a [PathStep] that represents a struct field access // on a field called [StructField.Name]. type StructField struct{ *structField } type structField struct { pathStep name string idx int // These fields are used for forcibly accessing an unexported field. // pvx, pvy, and field are only valid if unexported is true. unexported bool mayForce bool // Forcibly allow visibility paddr bool // Was parent addressable? pvx, pvy reflect.Value // Parent values (always addressable) field reflect.StructField // Field information } func (sf StructField) Type() reflect.Type { return sf.typ } func (sf StructField) Values() (vx, vy reflect.Value) { if !sf.unexported { return sf.vx, sf.vy // CanInterface reports true } // Forcibly obtain read-write access to an unexported struct field. if sf.mayForce { vx = retrieveUnexportedField(sf.pvx, sf.field, sf.paddr) vy = retrieveUnexportedField(sf.pvy, sf.field, sf.paddr) return vx, vy // CanInterface reports true } return sf.vx, sf.vy // CanInterface reports false } func (sf StructField) String() string { return fmt.Sprintf(".%s", sf.name) } // Name is the field name. func (sf StructField) Name() string { return sf.name } // Index is the index of the field in the parent struct type. // See [reflect.Type.Field]. func (sf StructField) Index() int { return sf.idx } // SliceIndex is a [PathStep] that represents an index operation on // a slice or array at some index [SliceIndex.Key]. type SliceIndex struct{ *sliceIndex } type sliceIndex struct { pathStep xkey, ykey int isSlice bool // False for reflect.Array } func (si SliceIndex) Type() reflect.Type { return si.typ } func (si SliceIndex) Values() (vx, vy reflect.Value) { return si.vx, si.vy } func (si SliceIndex) String() string { switch { case si.xkey == si.ykey: return fmt.Sprintf("[%d]", si.xkey) case si.ykey == -1: // [5->?] means "I don't know where X[5] went" return fmt.Sprintf("[%d->?]", si.xkey) case si.xkey == -1: // [?->3] means "I don't know where Y[3] came from" return fmt.Sprintf("[?->%d]", si.ykey) default: // [5->3] means "X[5] moved to Y[3]" return fmt.Sprintf("[%d->%d]", si.xkey, si.ykey) } } // Key is the index key; it may return -1 if in a split state func (si SliceIndex) Key() int { if si.xkey != si.ykey { return -1 } return si.xkey } // SplitKeys are the indexes for indexing into slices in the // x and y values, respectively. These indexes may differ due to the // insertion or removal of an element in one of the slices, causing // all of the indexes to be shifted. If an index is -1, then that // indicates that the element does not exist in the associated slice. // // [SliceIndex.Key] is guaranteed to return -1 if and only if the indexes // returned by SplitKeys are not the same. SplitKeys will never return -1 for // both indexes. func (si SliceIndex) SplitKeys() (ix, iy int) { return si.xkey, si.ykey } // MapIndex is a [PathStep] that represents an index operation on a map at some index Key. type MapIndex struct{ *mapIndex } type mapIndex struct { pathStep key reflect.Value } func (mi MapIndex) Type() reflect.Type { return mi.typ } func (mi MapIndex) Values() (vx, vy reflect.Value) { return mi.vx, mi.vy } func (mi MapIndex) String() string { return fmt.Sprintf("[%#v]", mi.key) } // Key is the value of the map key. func (mi MapIndex) Key() reflect.Value { return mi.key } // Indirect is a [PathStep] that represents pointer indirection on the parent type. type Indirect struct{ *indirect } type indirect struct { pathStep } func (in Indirect) Type() reflect.Type { return in.typ } func (in Indirect) Values() (vx, vy reflect.Value) { return in.vx, in.vy } func (in Indirect) String() string { return "*" } // TypeAssertion is a [PathStep] that represents a type assertion on an interface. type TypeAssertion struct{ *typeAssertion } type typeAssertion struct { pathStep } func (ta TypeAssertion) Type() reflect.Type { return ta.typ } func (ta TypeAssertion) Values() (vx, vy reflect.Value) { return ta.vx, ta.vy } func (ta TypeAssertion) String() string { return fmt.Sprintf(".(%v)", value.TypeString(ta.typ, false)) } // Transform is a [PathStep] that represents a transformation // from the parent type to the current type. type Transform struct{ *transform } type transform struct { pathStep trans *transformer } func (tf Transform) Type() reflect.Type { return tf.typ } func (tf Transform) Values() (vx, vy reflect.Value) { return tf.vx, tf.vy } func (tf Transform) String() string { return fmt.Sprintf("%s()", tf.trans.name) } // Name is the name of the [Transformer]. func (tf Transform) Name() string { return tf.trans.name } // Func is the function pointer to the transformer function. func (tf Transform) Func() reflect.Value { return tf.trans.fnc } // Option returns the originally constructed [Transformer] option. // The == operator can be used to detect the exact option used. func (tf Transform) Option() Option { return tf.trans } // pointerPath represents a dual-stack of pointers encountered when // recursively traversing the x and y values. This data structure supports // detection of cycles and determining whether the cycles are equal. // In Go, cycles can occur via pointers, slices, and maps. // // The pointerPath uses a map to represent a stack; where descension into a // pointer pushes the address onto the stack, and ascension from a pointer // pops the address from the stack. Thus, when traversing into a pointer from // reflect.Ptr, reflect.Slice element, or reflect.Map, we can detect cycles // by checking whether the pointer has already been visited. The cycle detection // uses a separate stack for the x and y values. // // If a cycle is detected we need to determine whether the two pointers // should be considered equal. The definition of equality chosen by Equal // requires two graphs to have the same structure. To determine this, both the // x and y values must have a cycle where the previous pointers were also // encountered together as a pair. // // Semantically, this is equivalent to augmenting Indirect, SliceIndex, and // MapIndex with pointer information for the x and y values. // Suppose px and py are two pointers to compare, we then search the // Path for whether px was ever encountered in the Path history of x, and // similarly so with py. If either side has a cycle, the comparison is only // equal if both px and py have a cycle resulting from the same PathStep. // // Using a map as a stack is more performant as we can perform cycle detection // in O(1) instead of O(N) where N is len(Path). type pointerPath struct { // mx is keyed by x pointers, where the value is the associated y pointer. mx map[value.Pointer]value.Pointer // my is keyed by y pointers, where the value is the associated x pointer. my map[value.Pointer]value.Pointer } func (p *pointerPath) Init() { p.mx = make(map[value.Pointer]value.Pointer) p.my = make(map[value.Pointer]value.Pointer) } // Push indicates intent to descend into pointers vx and vy where // visited reports whether either has been seen before. If visited before, // equal reports whether both pointers were encountered together. // Pop must be called if and only if the pointers were never visited. // // The pointers vx and vy must be a reflect.Ptr, reflect.Slice, or reflect.Map // and be non-nil. func (p pointerPath) Push(vx, vy reflect.Value) (equal, visited bool) { px := value.PointerOf(vx) py := value.PointerOf(vy) _, ok1 := p.mx[px] _, ok2 := p.my[py] if ok1 || ok2 { equal = p.mx[px] == py && p.my[py] == px // Pointers paired together return equal, true } p.mx[px] = py p.my[py] = px return false, false } // Pop ascends from pointers vx and vy. func (p pointerPath) Pop(vx, vy reflect.Value) { delete(p.mx, value.PointerOf(vx)) delete(p.my, value.PointerOf(vy)) } // isExported reports whether the identifier is exported. func isExported(id string) bool { r, _ := utf8.DecodeRuneInString(id) return unicode.IsUpper(r) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/go-cmp/cmp/report_text.go
vendor/github.com/google/go-cmp/cmp/report_text.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 cmp import ( "bytes" "fmt" "math/rand" "strings" "time" "unicode/utf8" "github.com/google/go-cmp/cmp/internal/flags" ) var randBool = rand.New(rand.NewSource(time.Now().Unix())).Intn(2) == 0 const maxColumnLength = 80 type indentMode int func (n indentMode) appendIndent(b []byte, d diffMode) []byte { // The output of Diff is documented as being unstable to provide future // flexibility in changing the output for more humanly readable reports. // This logic intentionally introduces instability to the exact output // so that users can detect accidental reliance on stability early on, // rather than much later when an actual change to the format occurs. if flags.Deterministic || randBool { // Use regular spaces (U+0020). switch d { case diffUnknown, diffIdentical: b = append(b, " "...) case diffRemoved: b = append(b, "- "...) case diffInserted: b = append(b, "+ "...) } } else { // Use non-breaking spaces (U+00a0). switch d { case diffUnknown, diffIdentical: b = append(b, "  "...) case diffRemoved: b = append(b, "- "...) case diffInserted: b = append(b, "+ "...) } } return repeatCount(n).appendChar(b, '\t') } type repeatCount int func (n repeatCount) appendChar(b []byte, c byte) []byte { for ; n > 0; n-- { b = append(b, c) } return b } // textNode is a simplified tree-based representation of structured text. // Possible node types are textWrap, textList, or textLine. type textNode interface { // Len reports the length in bytes of a single-line version of the tree. // Nested textRecord.Diff and textRecord.Comment fields are ignored. Len() int // Equal reports whether the two trees are structurally identical. // Nested textRecord.Diff and textRecord.Comment fields are compared. Equal(textNode) bool // String returns the string representation of the text tree. // It is not guaranteed that len(x.String()) == x.Len(), // nor that x.String() == y.String() implies that x.Equal(y). String() string // formatCompactTo formats the contents of the tree as a single-line string // to the provided buffer. Any nested textRecord.Diff and textRecord.Comment // fields are ignored. // // However, not all nodes in the tree should be collapsed as a single-line. // If a node can be collapsed as a single-line, it is replaced by a textLine // node. Since the top-level node cannot replace itself, this also returns // the current node itself. // // This does not mutate the receiver. formatCompactTo([]byte, diffMode) ([]byte, textNode) // formatExpandedTo formats the contents of the tree as a multi-line string // to the provided buffer. In order for column alignment to operate well, // formatCompactTo must be called before calling formatExpandedTo. formatExpandedTo([]byte, diffMode, indentMode) []byte } // textWrap is a wrapper that concatenates a prefix and/or a suffix // to the underlying node. type textWrap struct { Prefix string // e.g., "bytes.Buffer{" Value textNode // textWrap | textList | textLine Suffix string // e.g., "}" Metadata interface{} // arbitrary metadata; has no effect on formatting } func (s *textWrap) Len() int { return len(s.Prefix) + s.Value.Len() + len(s.Suffix) } func (s1 *textWrap) Equal(s2 textNode) bool { if s2, ok := s2.(*textWrap); ok { return s1.Prefix == s2.Prefix && s1.Value.Equal(s2.Value) && s1.Suffix == s2.Suffix } return false } func (s *textWrap) String() string { var d diffMode var n indentMode _, s2 := s.formatCompactTo(nil, d) b := n.appendIndent(nil, d) // Leading indent b = s2.formatExpandedTo(b, d, n) // Main body b = append(b, '\n') // Trailing newline return string(b) } func (s *textWrap) formatCompactTo(b []byte, d diffMode) ([]byte, textNode) { n0 := len(b) // Original buffer length b = append(b, s.Prefix...) b, s.Value = s.Value.formatCompactTo(b, d) b = append(b, s.Suffix...) if _, ok := s.Value.(textLine); ok { return b, textLine(b[n0:]) } return b, s } func (s *textWrap) formatExpandedTo(b []byte, d diffMode, n indentMode) []byte { b = append(b, s.Prefix...) b = s.Value.formatExpandedTo(b, d, n) b = append(b, s.Suffix...) return b } // textList is a comma-separated list of textWrap or textLine nodes. // The list may be formatted as multi-lines or single-line at the discretion // of the textList.formatCompactTo method. type textList []textRecord type textRecord struct { Diff diffMode // e.g., 0 or '-' or '+' Key string // e.g., "MyField" Value textNode // textWrap | textLine ElideComma bool // avoid trailing comma Comment fmt.Stringer // e.g., "6 identical fields" } // AppendEllipsis appends a new ellipsis node to the list if none already // exists at the end. If cs is non-zero it coalesces the statistics with the // previous diffStats. func (s *textList) AppendEllipsis(ds diffStats) { hasStats := !ds.IsZero() if len(*s) == 0 || !(*s)[len(*s)-1].Value.Equal(textEllipsis) { if hasStats { *s = append(*s, textRecord{Value: textEllipsis, ElideComma: true, Comment: ds}) } else { *s = append(*s, textRecord{Value: textEllipsis, ElideComma: true}) } return } if hasStats { (*s)[len(*s)-1].Comment = (*s)[len(*s)-1].Comment.(diffStats).Append(ds) } } func (s textList) Len() (n int) { for i, r := range s { n += len(r.Key) if r.Key != "" { n += len(": ") } n += r.Value.Len() if i < len(s)-1 { n += len(", ") } } return n } func (s1 textList) Equal(s2 textNode) bool { if s2, ok := s2.(textList); ok { if len(s1) != len(s2) { return false } for i := range s1 { r1, r2 := s1[i], s2[i] if !(r1.Diff == r2.Diff && r1.Key == r2.Key && r1.Value.Equal(r2.Value) && r1.Comment == r2.Comment) { return false } } return true } return false } func (s textList) String() string { return (&textWrap{Prefix: "{", Value: s, Suffix: "}"}).String() } func (s textList) formatCompactTo(b []byte, d diffMode) ([]byte, textNode) { s = append(textList(nil), s...) // Avoid mutating original // Determine whether we can collapse this list as a single line. n0 := len(b) // Original buffer length var multiLine bool for i, r := range s { if r.Diff == diffInserted || r.Diff == diffRemoved { multiLine = true } b = append(b, r.Key...) if r.Key != "" { b = append(b, ": "...) } b, s[i].Value = r.Value.formatCompactTo(b, d|r.Diff) if _, ok := s[i].Value.(textLine); !ok { multiLine = true } if r.Comment != nil { multiLine = true } if i < len(s)-1 { b = append(b, ", "...) } } // Force multi-lined output when printing a removed/inserted node that // is sufficiently long. if (d == diffInserted || d == diffRemoved) && len(b[n0:]) > maxColumnLength { multiLine = true } if !multiLine { return b, textLine(b[n0:]) } return b, s } func (s textList) formatExpandedTo(b []byte, d diffMode, n indentMode) []byte { alignKeyLens := s.alignLens( func(r textRecord) bool { _, isLine := r.Value.(textLine) return r.Key == "" || !isLine }, func(r textRecord) int { return utf8.RuneCountInString(r.Key) }, ) alignValueLens := s.alignLens( func(r textRecord) bool { _, isLine := r.Value.(textLine) return !isLine || r.Value.Equal(textEllipsis) || r.Comment == nil }, func(r textRecord) int { return utf8.RuneCount(r.Value.(textLine)) }, ) // Format lists of simple lists in a batched form. // If the list is sequence of only textLine values, // then batch multiple values on a single line. var isSimple bool for _, r := range s { _, isLine := r.Value.(textLine) isSimple = r.Diff == 0 && r.Key == "" && isLine && r.Comment == nil if !isSimple { break } } if isSimple { n++ var batch []byte emitBatch := func() { if len(batch) > 0 { b = n.appendIndent(append(b, '\n'), d) b = append(b, bytes.TrimRight(batch, " ")...) batch = batch[:0] } } for _, r := range s { line := r.Value.(textLine) if len(batch)+len(line)+len(", ") > maxColumnLength { emitBatch() } batch = append(batch, line...) batch = append(batch, ", "...) } emitBatch() n-- return n.appendIndent(append(b, '\n'), d) } // Format the list as a multi-lined output. n++ for i, r := range s { b = n.appendIndent(append(b, '\n'), d|r.Diff) if r.Key != "" { b = append(b, r.Key+": "...) } b = alignKeyLens[i].appendChar(b, ' ') b = r.Value.formatExpandedTo(b, d|r.Diff, n) if !r.ElideComma { b = append(b, ',') } b = alignValueLens[i].appendChar(b, ' ') if r.Comment != nil { b = append(b, " // "+r.Comment.String()...) } } n-- return n.appendIndent(append(b, '\n'), d) } func (s textList) alignLens( skipFunc func(textRecord) bool, lenFunc func(textRecord) int, ) []repeatCount { var startIdx, endIdx, maxLen int lens := make([]repeatCount, len(s)) for i, r := range s { if skipFunc(r) { for j := startIdx; j < endIdx && j < len(s); j++ { lens[j] = repeatCount(maxLen - lenFunc(s[j])) } startIdx, endIdx, maxLen = i+1, i+1, 0 } else { if maxLen < lenFunc(r) { maxLen = lenFunc(r) } endIdx = i + 1 } } for j := startIdx; j < endIdx && j < len(s); j++ { lens[j] = repeatCount(maxLen - lenFunc(s[j])) } return lens } // textLine is a single-line segment of text and is always a leaf node // in the textNode tree. type textLine []byte var ( textNil = textLine("nil") textEllipsis = textLine("...") ) func (s textLine) Len() int { return len(s) } func (s1 textLine) Equal(s2 textNode) bool { if s2, ok := s2.(textLine); ok { return bytes.Equal([]byte(s1), []byte(s2)) } return false } func (s textLine) String() string { return string(s) } func (s textLine) formatCompactTo(b []byte, d diffMode) ([]byte, textNode) { return append(b, s...), s } func (s textLine) formatExpandedTo(b []byte, _ diffMode, _ indentMode) []byte { return append(b, s...) } type diffStats struct { Name string NumIgnored int NumIdentical int NumRemoved int NumInserted int NumModified int } func (s diffStats) IsZero() bool { s.Name = "" return s == diffStats{} } func (s diffStats) NumDiff() int { return s.NumRemoved + s.NumInserted + s.NumModified } func (s diffStats) Append(ds diffStats) diffStats { assert(s.Name == ds.Name) s.NumIgnored += ds.NumIgnored s.NumIdentical += ds.NumIdentical s.NumRemoved += ds.NumRemoved s.NumInserted += ds.NumInserted s.NumModified += ds.NumModified return s } // String prints a humanly-readable summary of coalesced records. // // Example: // // diffStats{Name: "Field", NumIgnored: 5}.String() => "5 ignored fields" func (s diffStats) String() string { var ss []string var sum int labels := [...]string{"ignored", "identical", "removed", "inserted", "modified"} counts := [...]int{s.NumIgnored, s.NumIdentical, s.NumRemoved, s.NumInserted, s.NumModified} for i, n := range counts { if n > 0 { ss = append(ss, fmt.Sprintf("%d %v", n, labels[i])) } sum += n } // Pluralize the name (adjusting for some obscure English grammar rules). name := s.Name if sum > 1 { name += "s" if strings.HasSuffix(name, "ys") { name = name[:len(name)-2] + "ies" // e.g., "entrys" => "entries" } } // Format the list according to English grammar (with Oxford comma). switch n := len(ss); n { case 0: return "" case 1, 2: return strings.Join(ss, " and ") + " " + name default: return strings.Join(ss[:n-1], ", ") + ", and " + ss[n-1] + " " + name } } type commentString string func (s commentString) String() string { return string(s) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/go-cmp/cmp/report_value.go
vendor/github.com/google/go-cmp/cmp/report_value.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 cmp import "reflect" // valueNode represents a single node within a report, which is a // structured representation of the value tree, containing information // regarding which nodes are equal or not. type valueNode struct { parent *valueNode Type reflect.Type ValueX reflect.Value ValueY reflect.Value // NumSame is the number of leaf nodes that are equal. // All descendants are equal only if NumDiff is 0. NumSame int // NumDiff is the number of leaf nodes that are not equal. NumDiff int // NumIgnored is the number of leaf nodes that are ignored. NumIgnored int // NumCompared is the number of leaf nodes that were compared // using an Equal method or Comparer function. NumCompared int // NumTransformed is the number of non-leaf nodes that were transformed. NumTransformed int // NumChildren is the number of transitive descendants of this node. // This counts from zero; thus, leaf nodes have no descendants. NumChildren int // MaxDepth is the maximum depth of the tree. This counts from zero; // thus, leaf nodes have a depth of zero. MaxDepth int // Records is a list of struct fields, slice elements, or map entries. Records []reportRecord // If populated, implies Value is not populated // Value is the result of a transformation, pointer indirect, of // type assertion. Value *valueNode // If populated, implies Records is not populated // TransformerName is the name of the transformer. TransformerName string // If non-empty, implies Value is populated } type reportRecord struct { Key reflect.Value // Invalid for slice element Value *valueNode } func (parent *valueNode) PushStep(ps PathStep) (child *valueNode) { vx, vy := ps.Values() child = &valueNode{parent: parent, Type: ps.Type(), ValueX: vx, ValueY: vy} switch s := ps.(type) { case StructField: assert(parent.Value == nil) parent.Records = append(parent.Records, reportRecord{Key: reflect.ValueOf(s.Name()), Value: child}) case SliceIndex: assert(parent.Value == nil) parent.Records = append(parent.Records, reportRecord{Value: child}) case MapIndex: assert(parent.Value == nil) parent.Records = append(parent.Records, reportRecord{Key: s.Key(), Value: child}) case Indirect: assert(parent.Value == nil && parent.Records == nil) parent.Value = child case TypeAssertion: assert(parent.Value == nil && parent.Records == nil) parent.Value = child case Transform: assert(parent.Value == nil && parent.Records == nil) parent.Value = child parent.TransformerName = s.Name() parent.NumTransformed++ default: assert(parent == nil) // Must be the root step } return child } func (r *valueNode) Report(rs Result) { assert(r.MaxDepth == 0) // May only be called on leaf nodes if rs.ByIgnore() { r.NumIgnored++ } else { if rs.Equal() { r.NumSame++ } else { r.NumDiff++ } } assert(r.NumSame+r.NumDiff+r.NumIgnored == 1) if rs.ByMethod() { r.NumCompared++ } if rs.ByFunc() { r.NumCompared++ } assert(r.NumCompared <= 1) } func (child *valueNode) PopStep() (parent *valueNode) { if child.parent == nil { return nil } parent = child.parent parent.NumSame += child.NumSame parent.NumDiff += child.NumDiff parent.NumIgnored += child.NumIgnored parent.NumCompared += child.NumCompared parent.NumTransformed += child.NumTransformed parent.NumChildren += child.NumChildren + 1 if parent.MaxDepth < child.MaxDepth+1 { parent.MaxDepth = child.MaxDepth + 1 } return parent }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/go-cmp/cmp/compare.go
vendor/github.com/google/go-cmp/cmp/compare.go
// Copyright 2017, 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 cmp determines equality of values. // // This package is intended to be a more powerful and safer alternative to // [reflect.DeepEqual] for comparing whether two values are semantically equal. // It is intended to only be used in tests, as performance is not a goal and // it may panic if it cannot compare the values. Its propensity towards // panicking means that its unsuitable for production environments where a // spurious panic may be fatal. // // The primary features of cmp are: // // - When the default behavior of equality does not suit the test's needs, // custom equality functions can override the equality operation. // For example, an equality function may report floats as equal so long as // they are within some tolerance of each other. // // - Types with an Equal method (e.g., [time.Time.Equal]) may use that method // to determine equality. This allows package authors to determine // the equality operation for the types that they define. // // - If no custom equality functions are used and no Equal method is defined, // equality is determined by recursively comparing the primitive kinds on // both values, much like [reflect.DeepEqual]. Unlike [reflect.DeepEqual], // unexported fields are not compared by default; they result in panics // unless suppressed by using an [Ignore] option // (see [github.com/google/go-cmp/cmp/cmpopts.IgnoreUnexported]) // or explicitly compared using the [Exporter] option. package cmp import ( "fmt" "reflect" "strings" "github.com/google/go-cmp/cmp/internal/diff" "github.com/google/go-cmp/cmp/internal/function" "github.com/google/go-cmp/cmp/internal/value" ) // TODO(≥go1.18): Use any instead of interface{}. // Equal reports whether x and y are equal by recursively applying the // following rules in the given order to x and y and all of their sub-values: // // - Let S be the set of all [Ignore], [Transformer], and [Comparer] options that // remain after applying all path filters, value filters, and type filters. // If at least one [Ignore] exists in S, then the comparison is ignored. // If the number of [Transformer] and [Comparer] options in S is non-zero, // then Equal panics because it is ambiguous which option to use. // If S contains a single [Transformer], then use that to transform // the current values and recursively call Equal on the output values. // If S contains a single [Comparer], then use that to compare the current values. // Otherwise, evaluation proceeds to the next rule. // // - If the values have an Equal method of the form "(T) Equal(T) bool" or // "(T) Equal(I) bool" where T is assignable to I, then use the result of // x.Equal(y) even if x or y is nil. Otherwise, no such method exists and // evaluation proceeds to the next rule. // // - Lastly, try to compare x and y based on their basic kinds. // Simple kinds like booleans, integers, floats, complex numbers, strings, // and channels are compared using the equivalent of the == operator in Go. // Functions are only equal if they are both nil, otherwise they are unequal. // // Structs are equal if recursively calling Equal on all fields report equal. // If a struct contains unexported fields, Equal panics unless an [Ignore] option // (e.g., [github.com/google/go-cmp/cmp/cmpopts.IgnoreUnexported]) ignores that field // or the [Exporter] option explicitly permits comparing the unexported field. // // Slices are equal if they are both nil or both non-nil, where recursively // calling Equal on all non-ignored slice or array elements report equal. // Empty non-nil slices and nil slices are not equal; to equate empty slices, // consider using [github.com/google/go-cmp/cmp/cmpopts.EquateEmpty]. // // Maps are equal if they are both nil or both non-nil, where recursively // calling Equal on all non-ignored map entries report equal. // Map keys are equal according to the == operator. // To use custom comparisons for map keys, consider using // [github.com/google/go-cmp/cmp/cmpopts.SortMaps]. // Empty non-nil maps and nil maps are not equal; to equate empty maps, // consider using [github.com/google/go-cmp/cmp/cmpopts.EquateEmpty]. // // Pointers and interfaces are equal if they are both nil or both non-nil, // where they have the same underlying concrete type and recursively // calling Equal on the underlying values reports equal. // // Before recursing into a pointer, slice element, or map, the current path // is checked to detect whether the address has already been visited. // If there is a cycle, then the pointed at values are considered equal // only if both addresses were previously visited in the same path step. func Equal(x, y interface{}, opts ...Option) bool { s := newState(opts) s.compareAny(rootStep(x, y)) return s.result.Equal() } // Diff returns a human-readable report of the differences between two values: // y - x. It returns an empty string if and only if Equal returns true for the // same input values and options. // // The output is displayed as a literal in pseudo-Go syntax. // At the start of each line, a "-" prefix indicates an element removed from x, // a "+" prefix to indicates an element added from y, and the lack of a prefix // indicates an element common to both x and y. If possible, the output // uses fmt.Stringer.String or error.Error methods to produce more humanly // readable outputs. In such cases, the string is prefixed with either an // 's' or 'e' character, respectively, to indicate that the method was called. // // Do not depend on this output being stable. If you need the ability to // programmatically interpret the difference, consider using a custom Reporter. func Diff(x, y interface{}, opts ...Option) string { s := newState(opts) // Optimization: If there are no other reporters, we can optimize for the // common case where the result is equal (and thus no reported difference). // This avoids the expensive construction of a difference tree. if len(s.reporters) == 0 { s.compareAny(rootStep(x, y)) if s.result.Equal() { return "" } s.result = diff.Result{} // Reset results } r := new(defaultReporter) s.reporters = append(s.reporters, reporter{r}) s.compareAny(rootStep(x, y)) d := r.String() if (d == "") != s.result.Equal() { panic("inconsistent difference and equality results") } return d } // rootStep constructs the first path step. If x and y have differing types, // then they are stored within an empty interface type. func rootStep(x, y interface{}) PathStep { vx := reflect.ValueOf(x) vy := reflect.ValueOf(y) // If the inputs are different types, auto-wrap them in an empty interface // so that they have the same parent type. var t reflect.Type if !vx.IsValid() || !vy.IsValid() || vx.Type() != vy.Type() { t = anyType if vx.IsValid() { vvx := reflect.New(t).Elem() vvx.Set(vx) vx = vvx } if vy.IsValid() { vvy := reflect.New(t).Elem() vvy.Set(vy) vy = vvy } } else { t = vx.Type() } return &pathStep{t, vx, vy} } type state struct { // These fields represent the "comparison state". // Calling statelessCompare must not result in observable changes to these. result diff.Result // The current result of comparison curPath Path // The current path in the value tree curPtrs pointerPath // The current set of visited pointers reporters []reporter // Optional reporters // recChecker checks for infinite cycles applying the same set of // transformers upon the output of itself. recChecker recChecker // dynChecker triggers pseudo-random checks for option correctness. // It is safe for statelessCompare to mutate this value. dynChecker dynChecker // These fields, once set by processOption, will not change. exporters []exporter // List of exporters for structs with unexported fields opts Options // List of all fundamental and filter options } func newState(opts []Option) *state { // Always ensure a validator option exists to validate the inputs. s := &state{opts: Options{validator{}}} s.curPtrs.Init() s.processOption(Options(opts)) return s } func (s *state) processOption(opt Option) { switch opt := opt.(type) { case nil: case Options: for _, o := range opt { s.processOption(o) } case coreOption: type filtered interface { isFiltered() bool } if fopt, ok := opt.(filtered); ok && !fopt.isFiltered() { panic(fmt.Sprintf("cannot use an unfiltered option: %v", opt)) } s.opts = append(s.opts, opt) case exporter: s.exporters = append(s.exporters, opt) case reporter: s.reporters = append(s.reporters, opt) default: panic(fmt.Sprintf("unknown option %T", opt)) } } // statelessCompare compares two values and returns the result. // This function is stateless in that it does not alter the current result, // or output to any registered reporters. func (s *state) statelessCompare(step PathStep) diff.Result { // We do not save and restore curPath and curPtrs because all of the // compareX methods should properly push and pop from them. // It is an implementation bug if the contents of the paths differ from // when calling this function to when returning from it. oldResult, oldReporters := s.result, s.reporters s.result = diff.Result{} // Reset result s.reporters = nil // Remove reporters to avoid spurious printouts s.compareAny(step) res := s.result s.result, s.reporters = oldResult, oldReporters return res } func (s *state) compareAny(step PathStep) { // Update the path stack. s.curPath.push(step) defer s.curPath.pop() for _, r := range s.reporters { r.PushStep(step) defer r.PopStep() } s.recChecker.Check(s.curPath) // Cycle-detection for slice elements (see NOTE in compareSlice). t := step.Type() vx, vy := step.Values() if si, ok := step.(SliceIndex); ok && si.isSlice && vx.IsValid() && vy.IsValid() { px, py := vx.Addr(), vy.Addr() if eq, visited := s.curPtrs.Push(px, py); visited { s.report(eq, reportByCycle) return } defer s.curPtrs.Pop(px, py) } // Rule 1: Check whether an option applies on this node in the value tree. if s.tryOptions(t, vx, vy) { return } // Rule 2: Check whether the type has a valid Equal method. if s.tryMethod(t, vx, vy) { return } // Rule 3: Compare based on the underlying kind. switch t.Kind() { case reflect.Bool: s.report(vx.Bool() == vy.Bool(), 0) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: s.report(vx.Int() == vy.Int(), 0) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: s.report(vx.Uint() == vy.Uint(), 0) case reflect.Float32, reflect.Float64: s.report(vx.Float() == vy.Float(), 0) case reflect.Complex64, reflect.Complex128: s.report(vx.Complex() == vy.Complex(), 0) case reflect.String: s.report(vx.String() == vy.String(), 0) case reflect.Chan, reflect.UnsafePointer: s.report(vx.Pointer() == vy.Pointer(), 0) case reflect.Func: s.report(vx.IsNil() && vy.IsNil(), 0) case reflect.Struct: s.compareStruct(t, vx, vy) case reflect.Slice, reflect.Array: s.compareSlice(t, vx, vy) case reflect.Map: s.compareMap(t, vx, vy) case reflect.Ptr: s.comparePtr(t, vx, vy) case reflect.Interface: s.compareInterface(t, vx, vy) default: panic(fmt.Sprintf("%v kind not handled", t.Kind())) } } func (s *state) tryOptions(t reflect.Type, vx, vy reflect.Value) bool { // Evaluate all filters and apply the remaining options. if opt := s.opts.filter(s, t, vx, vy); opt != nil { opt.apply(s, vx, vy) return true } return false } func (s *state) tryMethod(t reflect.Type, vx, vy reflect.Value) bool { // Check if this type even has an Equal method. m, ok := t.MethodByName("Equal") if !ok || !function.IsType(m.Type, function.EqualAssignable) { return false } eq := s.callTTBFunc(m.Func, vx, vy) s.report(eq, reportByMethod) return true } func (s *state) callTRFunc(f, v reflect.Value, step Transform) reflect.Value { if !s.dynChecker.Next() { return f.Call([]reflect.Value{v})[0] } // Run the function twice and ensure that we get the same results back. // We run in goroutines so that the race detector (if enabled) can detect // unsafe mutations to the input. c := make(chan reflect.Value) go detectRaces(c, f, v) got := <-c want := f.Call([]reflect.Value{v})[0] if step.vx, step.vy = got, want; !s.statelessCompare(step).Equal() { // To avoid false-positives with non-reflexive equality operations, // we sanity check whether a value is equal to itself. if step.vx, step.vy = want, want; !s.statelessCompare(step).Equal() { return want } panic(fmt.Sprintf("non-deterministic function detected: %s", function.NameOf(f))) } return want } func (s *state) callTTBFunc(f, x, y reflect.Value) bool { if !s.dynChecker.Next() { return f.Call([]reflect.Value{x, y})[0].Bool() } // Swapping the input arguments is sufficient to check that // f is symmetric and deterministic. // We run in goroutines so that the race detector (if enabled) can detect // unsafe mutations to the input. c := make(chan reflect.Value) go detectRaces(c, f, y, x) got := <-c want := f.Call([]reflect.Value{x, y})[0].Bool() if !got.IsValid() || got.Bool() != want { panic(fmt.Sprintf("non-deterministic or non-symmetric function detected: %s", function.NameOf(f))) } return want } func detectRaces(c chan<- reflect.Value, f reflect.Value, vs ...reflect.Value) { var ret reflect.Value defer func() { recover() // Ignore panics, let the other call to f panic instead c <- ret }() ret = f.Call(vs)[0] } func (s *state) compareStruct(t reflect.Type, vx, vy reflect.Value) { var addr bool var vax, vay reflect.Value // Addressable versions of vx and vy var mayForce, mayForceInit bool step := StructField{&structField{}} for i := 0; i < t.NumField(); i++ { step.typ = t.Field(i).Type step.vx = vx.Field(i) step.vy = vy.Field(i) step.name = t.Field(i).Name step.idx = i step.unexported = !isExported(step.name) if step.unexported { if step.name == "_" { continue } // Defer checking of unexported fields until later to give an // Ignore a chance to ignore the field. if !vax.IsValid() || !vay.IsValid() { // For retrieveUnexportedField to work, the parent struct must // be addressable. Create a new copy of the values if // necessary to make them addressable. addr = vx.CanAddr() || vy.CanAddr() vax = makeAddressable(vx) vay = makeAddressable(vy) } if !mayForceInit { for _, xf := range s.exporters { mayForce = mayForce || xf(t) } mayForceInit = true } step.mayForce = mayForce step.paddr = addr step.pvx = vax step.pvy = vay step.field = t.Field(i) } s.compareAny(step) } } func (s *state) compareSlice(t reflect.Type, vx, vy reflect.Value) { isSlice := t.Kind() == reflect.Slice if isSlice && (vx.IsNil() || vy.IsNil()) { s.report(vx.IsNil() && vy.IsNil(), 0) return } // NOTE: It is incorrect to call curPtrs.Push on the slice header pointer // since slices represents a list of pointers, rather than a single pointer. // The pointer checking logic must be handled on a per-element basis // in compareAny. // // A slice header (see reflect.SliceHeader) in Go is a tuple of a starting // pointer P, a length N, and a capacity C. Supposing each slice element has // a memory size of M, then the slice is equivalent to the list of pointers: // [P+i*M for i in range(N)] // // For example, v[:0] and v[:1] are slices with the same starting pointer, // but they are clearly different values. Using the slice pointer alone // violates the assumption that equal pointers implies equal values. step := SliceIndex{&sliceIndex{pathStep: pathStep{typ: t.Elem()}, isSlice: isSlice}} withIndexes := func(ix, iy int) SliceIndex { if ix >= 0 { step.vx, step.xkey = vx.Index(ix), ix } else { step.vx, step.xkey = reflect.Value{}, -1 } if iy >= 0 { step.vy, step.ykey = vy.Index(iy), iy } else { step.vy, step.ykey = reflect.Value{}, -1 } return step } // Ignore options are able to ignore missing elements in a slice. // However, detecting these reliably requires an optimal differencing // algorithm, for which diff.Difference is not. // // Instead, we first iterate through both slices to detect which elements // would be ignored if standing alone. The index of non-discarded elements // are stored in a separate slice, which diffing is then performed on. var indexesX, indexesY []int var ignoredX, ignoredY []bool for ix := 0; ix < vx.Len(); ix++ { ignored := s.statelessCompare(withIndexes(ix, -1)).NumDiff == 0 if !ignored { indexesX = append(indexesX, ix) } ignoredX = append(ignoredX, ignored) } for iy := 0; iy < vy.Len(); iy++ { ignored := s.statelessCompare(withIndexes(-1, iy)).NumDiff == 0 if !ignored { indexesY = append(indexesY, iy) } ignoredY = append(ignoredY, ignored) } // Compute an edit-script for slices vx and vy (excluding ignored elements). edits := diff.Difference(len(indexesX), len(indexesY), func(ix, iy int) diff.Result { return s.statelessCompare(withIndexes(indexesX[ix], indexesY[iy])) }) // Replay the ignore-scripts and the edit-script. var ix, iy int for ix < vx.Len() || iy < vy.Len() { var e diff.EditType switch { case ix < len(ignoredX) && ignoredX[ix]: e = diff.UniqueX case iy < len(ignoredY) && ignoredY[iy]: e = diff.UniqueY default: e, edits = edits[0], edits[1:] } switch e { case diff.UniqueX: s.compareAny(withIndexes(ix, -1)) ix++ case diff.UniqueY: s.compareAny(withIndexes(-1, iy)) iy++ default: s.compareAny(withIndexes(ix, iy)) ix++ iy++ } } } func (s *state) compareMap(t reflect.Type, vx, vy reflect.Value) { if vx.IsNil() || vy.IsNil() { s.report(vx.IsNil() && vy.IsNil(), 0) return } // Cycle-detection for maps. if eq, visited := s.curPtrs.Push(vx, vy); visited { s.report(eq, reportByCycle) return } defer s.curPtrs.Pop(vx, vy) // We combine and sort the two map keys so that we can perform the // comparisons in a deterministic order. step := MapIndex{&mapIndex{pathStep: pathStep{typ: t.Elem()}}} for _, k := range value.SortKeys(append(vx.MapKeys(), vy.MapKeys()...)) { step.vx = vx.MapIndex(k) step.vy = vy.MapIndex(k) step.key = k if !step.vx.IsValid() && !step.vy.IsValid() { // It is possible for both vx and vy to be invalid if the // key contained a NaN value in it. // // Even with the ability to retrieve NaN keys in Go 1.12, // there still isn't a sensible way to compare the values since // a NaN key may map to multiple unordered values. // The most reasonable way to compare NaNs would be to compare the // set of values. However, this is impossible to do efficiently // since set equality is provably an O(n^2) operation given only // an Equal function. If we had a Less function or Hash function, // this could be done in O(n*log(n)) or O(n), respectively. // // Rather than adding complex logic to deal with NaNs, make it // the user's responsibility to compare such obscure maps. const help = "consider providing a Comparer to compare the map" panic(fmt.Sprintf("%#v has map key with NaNs\n%s", s.curPath, help)) } s.compareAny(step) } } func (s *state) comparePtr(t reflect.Type, vx, vy reflect.Value) { if vx.IsNil() || vy.IsNil() { s.report(vx.IsNil() && vy.IsNil(), 0) return } // Cycle-detection for pointers. if eq, visited := s.curPtrs.Push(vx, vy); visited { s.report(eq, reportByCycle) return } defer s.curPtrs.Pop(vx, vy) vx, vy = vx.Elem(), vy.Elem() s.compareAny(Indirect{&indirect{pathStep{t.Elem(), vx, vy}}}) } func (s *state) compareInterface(t reflect.Type, vx, vy reflect.Value) { if vx.IsNil() || vy.IsNil() { s.report(vx.IsNil() && vy.IsNil(), 0) return } vx, vy = vx.Elem(), vy.Elem() if vx.Type() != vy.Type() { s.report(false, 0) return } s.compareAny(TypeAssertion{&typeAssertion{pathStep{vx.Type(), vx, vy}}}) } func (s *state) report(eq bool, rf resultFlags) { if rf&reportByIgnore == 0 { if eq { s.result.NumSame++ rf |= reportEqual } else { s.result.NumDiff++ rf |= reportUnequal } } for _, r := range s.reporters { r.Report(Result{flags: rf}) } } // recChecker tracks the state needed to periodically perform checks that // user provided transformers are not stuck in an infinitely recursive cycle. type recChecker struct{ next int } // Check scans the Path for any recursive transformers and panics when any // recursive transformers are detected. Note that the presence of a // recursive Transformer does not necessarily imply an infinite cycle. // As such, this check only activates after some minimal number of path steps. func (rc *recChecker) Check(p Path) { const minLen = 1 << 16 if rc.next == 0 { rc.next = minLen } if len(p) < rc.next { return } rc.next <<= 1 // Check whether the same transformer has appeared at least twice. var ss []string m := map[Option]int{} for _, ps := range p { if t, ok := ps.(Transform); ok { t := t.Option() if m[t] == 1 { // Transformer was used exactly once before tf := t.(*transformer).fnc.Type() ss = append(ss, fmt.Sprintf("%v: %v => %v", t, tf.In(0), tf.Out(0))) } m[t]++ } } if len(ss) > 0 { const warning = "recursive set of Transformers detected" const help = "consider using cmpopts.AcyclicTransformer" set := strings.Join(ss, "\n\t") panic(fmt.Sprintf("%s:\n\t%s\n%s", warning, set, help)) } } // dynChecker tracks the state needed to periodically perform checks that // user provided functions are symmetric and deterministic. // The zero value is safe for immediate use. type dynChecker struct{ curr, next int } // Next increments the state and reports whether a check should be performed. // // Checks occur every Nth function call, where N is a triangular number: // // 0 1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136 153 171 190 ... // // See https://en.wikipedia.org/wiki/Triangular_number // // This sequence ensures that the cost of checks drops significantly as // the number of functions calls grows larger. func (dc *dynChecker) Next() bool { ok := dc.curr == dc.next if ok { dc.curr = 0 dc.next++ } dc.curr++ return ok } // makeAddressable returns a value that is always addressable. // It returns the input verbatim if it is already addressable, // otherwise it creates a new value and returns an addressable copy. func makeAddressable(v reflect.Value) reflect.Value { if v.CanAddr() { return v } vc := reflect.New(v.Type()).Elem() vc.Set(v) return vc }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/go-cmp/cmp/report_slices.go
vendor/github.com/google/go-cmp/cmp/report_slices.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 cmp import ( "bytes" "fmt" "math" "reflect" "strconv" "strings" "unicode" "unicode/utf8" "github.com/google/go-cmp/cmp/internal/diff" ) // CanFormatDiffSlice reports whether we support custom formatting for nodes // that are slices of primitive kinds or strings. func (opts formatOptions) CanFormatDiffSlice(v *valueNode) bool { switch { case opts.DiffMode != diffUnknown: return false // Must be formatting in diff mode case v.NumDiff == 0: return false // No differences detected case !v.ValueX.IsValid() || !v.ValueY.IsValid(): return false // Both values must be valid case v.NumIgnored > 0: return false // Some ignore option was used case v.NumTransformed > 0: return false // Some transform option was used case v.NumCompared > 1: return false // More than one comparison was used case v.NumCompared == 1 && v.Type.Name() != "": // The need for cmp to check applicability of options on every element // in a slice is a significant performance detriment for large []byte. // The workaround is to specify Comparer(bytes.Equal), // which enables cmp to compare []byte more efficiently. // If they differ, we still want to provide batched diffing. // The logic disallows named types since they tend to have their own // String method, with nicer formatting than what this provides. return false } // Check whether this is an interface with the same concrete types. t := v.Type vx, vy := v.ValueX, v.ValueY if t.Kind() == reflect.Interface && !vx.IsNil() && !vy.IsNil() && vx.Elem().Type() == vy.Elem().Type() { vx, vy = vx.Elem(), vy.Elem() t = vx.Type() } // Check whether we provide specialized diffing for this type. switch t.Kind() { case reflect.String: case reflect.Array, reflect.Slice: // Only slices of primitive types have specialized handling. switch t.Elem().Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Bool, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: default: return false } // Both slice values have to be non-empty. if t.Kind() == reflect.Slice && (vx.Len() == 0 || vy.Len() == 0) { return false } // If a sufficient number of elements already differ, // use specialized formatting even if length requirement is not met. if v.NumDiff > v.NumSame { return true } default: return false } // Use specialized string diffing for longer slices or strings. const minLength = 32 return vx.Len() >= minLength && vy.Len() >= minLength } // FormatDiffSlice prints a diff for the slices (or strings) represented by v. // This provides custom-tailored logic to make printing of differences in // textual strings and slices of primitive kinds more readable. func (opts formatOptions) FormatDiffSlice(v *valueNode) textNode { assert(opts.DiffMode == diffUnknown) t, vx, vy := v.Type, v.ValueX, v.ValueY if t.Kind() == reflect.Interface { vx, vy = vx.Elem(), vy.Elem() t = vx.Type() opts = opts.WithTypeMode(emitType) } // Auto-detect the type of the data. var sx, sy string var ssx, ssy []string var isString, isMostlyText, isPureLinedText, isBinary bool switch { case t.Kind() == reflect.String: sx, sy = vx.String(), vy.String() isString = true case t.Kind() == reflect.Slice && t.Elem() == byteType: sx, sy = string(vx.Bytes()), string(vy.Bytes()) isString = true case t.Kind() == reflect.Array: // Arrays need to be addressable for slice operations to work. vx2, vy2 := reflect.New(t).Elem(), reflect.New(t).Elem() vx2.Set(vx) vy2.Set(vy) vx, vy = vx2, vy2 } if isString { var numTotalRunes, numValidRunes, numLines, lastLineIdx, maxLineLen int for i, r := range sx + sy { numTotalRunes++ if (unicode.IsPrint(r) || unicode.IsSpace(r)) && r != utf8.RuneError { numValidRunes++ } if r == '\n' { if maxLineLen < i-lastLineIdx { maxLineLen = i - lastLineIdx } lastLineIdx = i + 1 numLines++ } } isPureText := numValidRunes == numTotalRunes isMostlyText = float64(numValidRunes) > math.Floor(0.90*float64(numTotalRunes)) isPureLinedText = isPureText && numLines >= 4 && maxLineLen <= 1024 isBinary = !isMostlyText // Avoid diffing by lines if it produces a significantly more complex // edit script than diffing by bytes. if isPureLinedText { ssx = strings.Split(sx, "\n") ssy = strings.Split(sy, "\n") esLines := diff.Difference(len(ssx), len(ssy), func(ix, iy int) diff.Result { return diff.BoolResult(ssx[ix] == ssy[iy]) }) esBytes := diff.Difference(len(sx), len(sy), func(ix, iy int) diff.Result { return diff.BoolResult(sx[ix] == sy[iy]) }) efficiencyLines := float64(esLines.Dist()) / float64(len(esLines)) efficiencyBytes := float64(esBytes.Dist()) / float64(len(esBytes)) quotedLength := len(strconv.Quote(sx + sy)) unquotedLength := len(sx) + len(sy) escapeExpansionRatio := float64(quotedLength) / float64(unquotedLength) isPureLinedText = efficiencyLines < 4*efficiencyBytes || escapeExpansionRatio > 1.1 } } // Format the string into printable records. var list textList var delim string switch { // If the text appears to be multi-lined text, // then perform differencing across individual lines. case isPureLinedText: list = opts.formatDiffSlice( reflect.ValueOf(ssx), reflect.ValueOf(ssy), 1, "line", func(v reflect.Value, d diffMode) textRecord { s := formatString(v.Index(0).String()) return textRecord{Diff: d, Value: textLine(s)} }, ) delim = "\n" // If possible, use a custom triple-quote (""") syntax for printing // differences in a string literal. This format is more readable, // but has edge-cases where differences are visually indistinguishable. // This format is avoided under the following conditions: // - A line starts with `"""` // - A line starts with "..." // - A line contains non-printable characters // - Adjacent different lines differ only by whitespace // // For example: // // """ // ... // 3 identical lines // foo // bar // - baz // + BAZ // """ isTripleQuoted := true prevRemoveLines := map[string]bool{} prevInsertLines := map[string]bool{} var list2 textList list2 = append(list2, textRecord{Value: textLine(`"""`), ElideComma: true}) for _, r := range list { if !r.Value.Equal(textEllipsis) { line, _ := strconv.Unquote(string(r.Value.(textLine))) line = strings.TrimPrefix(strings.TrimSuffix(line, "\r"), "\r") // trim leading/trailing carriage returns for legacy Windows endline support normLine := strings.Map(func(r rune) rune { if unicode.IsSpace(r) { return -1 // drop whitespace to avoid visually indistinguishable output } return r }, line) isPrintable := func(r rune) bool { return unicode.IsPrint(r) || r == '\t' // specially treat tab as printable } isTripleQuoted = !strings.HasPrefix(line, `"""`) && !strings.HasPrefix(line, "...") && strings.TrimFunc(line, isPrintable) == "" switch r.Diff { case diffRemoved: isTripleQuoted = isTripleQuoted && !prevInsertLines[normLine] prevRemoveLines[normLine] = true case diffInserted: isTripleQuoted = isTripleQuoted && !prevRemoveLines[normLine] prevInsertLines[normLine] = true } if !isTripleQuoted { break } r.Value = textLine(line) r.ElideComma = true } if !(r.Diff == diffRemoved || r.Diff == diffInserted) { // start a new non-adjacent difference group prevRemoveLines = map[string]bool{} prevInsertLines = map[string]bool{} } list2 = append(list2, r) } if r := list2[len(list2)-1]; r.Diff == diffIdentical && len(r.Value.(textLine)) == 0 { list2 = list2[:len(list2)-1] // elide single empty line at the end } list2 = append(list2, textRecord{Value: textLine(`"""`), ElideComma: true}) if isTripleQuoted { var out textNode = &textWrap{Prefix: "(", Value: list2, Suffix: ")"} switch t.Kind() { case reflect.String: if t != stringType { out = opts.FormatType(t, out) } case reflect.Slice: // Always emit type for slices since the triple-quote syntax // looks like a string (not a slice). opts = opts.WithTypeMode(emitType) out = opts.FormatType(t, out) } return out } // If the text appears to be single-lined text, // then perform differencing in approximately fixed-sized chunks. // The output is printed as quoted strings. case isMostlyText: list = opts.formatDiffSlice( reflect.ValueOf(sx), reflect.ValueOf(sy), 64, "byte", func(v reflect.Value, d diffMode) textRecord { s := formatString(v.String()) return textRecord{Diff: d, Value: textLine(s)} }, ) // If the text appears to be binary data, // then perform differencing in approximately fixed-sized chunks. // The output is inspired by hexdump. case isBinary: list = opts.formatDiffSlice( reflect.ValueOf(sx), reflect.ValueOf(sy), 16, "byte", func(v reflect.Value, d diffMode) textRecord { var ss []string for i := 0; i < v.Len(); i++ { ss = append(ss, formatHex(v.Index(i).Uint())) } s := strings.Join(ss, ", ") comment := commentString(fmt.Sprintf("%c|%v|", d, formatASCII(v.String()))) return textRecord{Diff: d, Value: textLine(s), Comment: comment} }, ) // For all other slices of primitive types, // then perform differencing in approximately fixed-sized chunks. // The size of each chunk depends on the width of the element kind. default: var chunkSize int if t.Elem().Kind() == reflect.Bool { chunkSize = 16 } else { switch t.Elem().Bits() { case 8: chunkSize = 16 case 16: chunkSize = 12 case 32: chunkSize = 8 default: chunkSize = 8 } } list = opts.formatDiffSlice( vx, vy, chunkSize, t.Elem().Kind().String(), func(v reflect.Value, d diffMode) textRecord { var ss []string for i := 0; i < v.Len(); i++ { switch t.Elem().Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: ss = append(ss, fmt.Sprint(v.Index(i).Int())) case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64: ss = append(ss, fmt.Sprint(v.Index(i).Uint())) case reflect.Uint8, reflect.Uintptr: ss = append(ss, formatHex(v.Index(i).Uint())) case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: ss = append(ss, fmt.Sprint(v.Index(i).Interface())) } } s := strings.Join(ss, ", ") return textRecord{Diff: d, Value: textLine(s)} }, ) } // Wrap the output with appropriate type information. var out textNode = &textWrap{Prefix: "{", Value: list, Suffix: "}"} if !isMostlyText { // The "{...}" byte-sequence literal is not valid Go syntax for strings. // Emit the type for extra clarity (e.g. "string{...}"). if t.Kind() == reflect.String { opts = opts.WithTypeMode(emitType) } return opts.FormatType(t, out) } switch t.Kind() { case reflect.String: out = &textWrap{Prefix: "strings.Join(", Value: out, Suffix: fmt.Sprintf(", %q)", delim)} if t != stringType { out = opts.FormatType(t, out) } case reflect.Slice: out = &textWrap{Prefix: "bytes.Join(", Value: out, Suffix: fmt.Sprintf(", %q)", delim)} if t != bytesType { out = opts.FormatType(t, out) } } return out } // formatASCII formats s as an ASCII string. // This is useful for printing binary strings in a semi-legible way. func formatASCII(s string) string { b := bytes.Repeat([]byte{'.'}, len(s)) for i := 0; i < len(s); i++ { if ' ' <= s[i] && s[i] <= '~' { b[i] = s[i] } } return string(b) } func (opts formatOptions) formatDiffSlice( vx, vy reflect.Value, chunkSize int, name string, makeRec func(reflect.Value, diffMode) textRecord, ) (list textList) { eq := func(ix, iy int) bool { return vx.Index(ix).Interface() == vy.Index(iy).Interface() } es := diff.Difference(vx.Len(), vy.Len(), func(ix, iy int) diff.Result { return diff.BoolResult(eq(ix, iy)) }) appendChunks := func(v reflect.Value, d diffMode) int { n0 := v.Len() for v.Len() > 0 { n := chunkSize if n > v.Len() { n = v.Len() } list = append(list, makeRec(v.Slice(0, n), d)) v = v.Slice(n, v.Len()) } return n0 - v.Len() } var numDiffs int maxLen := -1 if opts.LimitVerbosity { maxLen = (1 << opts.verbosity()) << 2 // 4, 8, 16, 32, 64, etc... opts.VerbosityLevel-- } groups := coalesceAdjacentEdits(name, es) groups = coalesceInterveningIdentical(groups, chunkSize/4) groups = cleanupSurroundingIdentical(groups, eq) maxGroup := diffStats{Name: name} for i, ds := range groups { if maxLen >= 0 && numDiffs >= maxLen { maxGroup = maxGroup.Append(ds) continue } // Print equal. if ds.NumDiff() == 0 { // Compute the number of leading and trailing equal bytes to print. var numLo, numHi int numEqual := ds.NumIgnored + ds.NumIdentical for numLo < chunkSize*numContextRecords && numLo+numHi < numEqual && i != 0 { numLo++ } for numHi < chunkSize*numContextRecords && numLo+numHi < numEqual && i != len(groups)-1 { numHi++ } if numEqual-(numLo+numHi) <= chunkSize && ds.NumIgnored == 0 { numHi = numEqual - numLo // Avoid pointless coalescing of single equal row } // Print the equal bytes. appendChunks(vx.Slice(0, numLo), diffIdentical) if numEqual > numLo+numHi { ds.NumIdentical -= numLo + numHi list.AppendEllipsis(ds) } appendChunks(vx.Slice(numEqual-numHi, numEqual), diffIdentical) vx = vx.Slice(numEqual, vx.Len()) vy = vy.Slice(numEqual, vy.Len()) continue } // Print unequal. len0 := len(list) nx := appendChunks(vx.Slice(0, ds.NumIdentical+ds.NumRemoved+ds.NumModified), diffRemoved) vx = vx.Slice(nx, vx.Len()) ny := appendChunks(vy.Slice(0, ds.NumIdentical+ds.NumInserted+ds.NumModified), diffInserted) vy = vy.Slice(ny, vy.Len()) numDiffs += len(list) - len0 } if maxGroup.IsZero() { assert(vx.Len() == 0 && vy.Len() == 0) } else { list.AppendEllipsis(maxGroup) } return list } // coalesceAdjacentEdits coalesces the list of edits into groups of adjacent // equal or unequal counts. // // Example: // // Input: "..XXY...Y" // Output: [ // {NumIdentical: 2}, // {NumRemoved: 2, NumInserted 1}, // {NumIdentical: 3}, // {NumInserted: 1}, // ] func coalesceAdjacentEdits(name string, es diff.EditScript) (groups []diffStats) { var prevMode byte lastStats := func(mode byte) *diffStats { if prevMode != mode { groups = append(groups, diffStats{Name: name}) prevMode = mode } return &groups[len(groups)-1] } for _, e := range es { switch e { case diff.Identity: lastStats('=').NumIdentical++ case diff.UniqueX: lastStats('!').NumRemoved++ case diff.UniqueY: lastStats('!').NumInserted++ case diff.Modified: lastStats('!').NumModified++ } } return groups } // coalesceInterveningIdentical coalesces sufficiently short (<= windowSize) // equal groups into adjacent unequal groups that currently result in a // dual inserted/removed printout. This acts as a high-pass filter to smooth // out high-frequency changes within the windowSize. // // Example: // // WindowSize: 16, // Input: [ // {NumIdentical: 61}, // group 0 // {NumRemoved: 3, NumInserted: 1}, // group 1 // {NumIdentical: 6}, // ├── coalesce // {NumInserted: 2}, // ├── coalesce // {NumIdentical: 1}, // ├── coalesce // {NumRemoved: 9}, // └── coalesce // {NumIdentical: 64}, // group 2 // {NumRemoved: 3, NumInserted: 1}, // group 3 // {NumIdentical: 6}, // ├── coalesce // {NumInserted: 2}, // ├── coalesce // {NumIdentical: 1}, // ├── coalesce // {NumRemoved: 7}, // ├── coalesce // {NumIdentical: 1}, // ├── coalesce // {NumRemoved: 2}, // └── coalesce // {NumIdentical: 63}, // group 4 // ] // Output: [ // {NumIdentical: 61}, // {NumIdentical: 7, NumRemoved: 12, NumInserted: 3}, // {NumIdentical: 64}, // {NumIdentical: 8, NumRemoved: 12, NumInserted: 3}, // {NumIdentical: 63}, // ] func coalesceInterveningIdentical(groups []diffStats, windowSize int) []diffStats { groups, groupsOrig := groups[:0], groups for i, ds := range groupsOrig { if len(groups) >= 2 && ds.NumDiff() > 0 { prev := &groups[len(groups)-2] // Unequal group curr := &groups[len(groups)-1] // Equal group next := &groupsOrig[i] // Unequal group hadX, hadY := prev.NumRemoved > 0, prev.NumInserted > 0 hasX, hasY := next.NumRemoved > 0, next.NumInserted > 0 if ((hadX || hasX) && (hadY || hasY)) && curr.NumIdentical <= windowSize { *prev = prev.Append(*curr).Append(*next) groups = groups[:len(groups)-1] // Truncate off equal group continue } } groups = append(groups, ds) } return groups } // cleanupSurroundingIdentical scans through all unequal groups, and // moves any leading sequence of equal elements to the preceding equal group and // moves and trailing sequence of equal elements to the succeeding equal group. // // This is necessary since coalesceInterveningIdentical may coalesce edit groups // together such that leading/trailing spans of equal elements becomes possible. // Note that this can occur even with an optimal diffing algorithm. // // Example: // // Input: [ // {NumIdentical: 61}, // {NumIdentical: 1 , NumRemoved: 11, NumInserted: 2}, // assume 3 leading identical elements // {NumIdentical: 67}, // {NumIdentical: 7, NumRemoved: 12, NumInserted: 3}, // assume 10 trailing identical elements // {NumIdentical: 54}, // ] // Output: [ // {NumIdentical: 64}, // incremented by 3 // {NumRemoved: 9}, // {NumIdentical: 67}, // {NumRemoved: 9}, // {NumIdentical: 64}, // incremented by 10 // ] func cleanupSurroundingIdentical(groups []diffStats, eq func(i, j int) bool) []diffStats { var ix, iy int // indexes into sequence x and y for i, ds := range groups { // Handle equal group. if ds.NumDiff() == 0 { ix += ds.NumIdentical iy += ds.NumIdentical continue } // Handle unequal group. nx := ds.NumIdentical + ds.NumRemoved + ds.NumModified ny := ds.NumIdentical + ds.NumInserted + ds.NumModified var numLeadingIdentical, numTrailingIdentical int for j := 0; j < nx && j < ny && eq(ix+j, iy+j); j++ { numLeadingIdentical++ } for j := 0; j < nx && j < ny && eq(ix+nx-1-j, iy+ny-1-j); j++ { numTrailingIdentical++ } if numIdentical := numLeadingIdentical + numTrailingIdentical; numIdentical > 0 { if numLeadingIdentical > 0 { // Remove leading identical span from this group and // insert it into the preceding group. if i-1 >= 0 { groups[i-1].NumIdentical += numLeadingIdentical } else { // No preceding group exists, so prepend a new group, // but do so after we finish iterating over all groups. defer func() { groups = append([]diffStats{{Name: groups[0].Name, NumIdentical: numLeadingIdentical}}, groups...) }() } // Increment indexes since the preceding group would have handled this. ix += numLeadingIdentical iy += numLeadingIdentical } if numTrailingIdentical > 0 { // Remove trailing identical span from this group and // insert it into the succeeding group. if i+1 < len(groups) { groups[i+1].NumIdentical += numTrailingIdentical } else { // No succeeding group exists, so append a new group, // but do so after we finish iterating over all groups. defer func() { groups = append(groups, diffStats{Name: groups[len(groups)-1].Name, NumIdentical: numTrailingIdentical}) }() } // Do not increment indexes since the succeeding group will handle this. } // Update this group since some identical elements were removed. nx -= numIdentical ny -= numIdentical groups[i] = diffStats{Name: ds.Name, NumRemoved: nx, NumInserted: ny} } ix += nx iy += ny } return groups }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/go-cmp/cmp/options.go
vendor/github.com/google/go-cmp/cmp/options.go
// Copyright 2017, 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 cmp import ( "fmt" "reflect" "regexp" "strings" "github.com/google/go-cmp/cmp/internal/function" ) // Option configures for specific behavior of [Equal] and [Diff]. In particular, // the fundamental Option functions ([Ignore], [Transformer], and [Comparer]), // configure how equality is determined. // // The fundamental options may be composed with filters ([FilterPath] and // [FilterValues]) to control the scope over which they are applied. // // The [github.com/google/go-cmp/cmp/cmpopts] package provides helper functions // for creating options that may be used with [Equal] and [Diff]. type Option interface { // filter applies all filters and returns the option that remains. // Each option may only read s.curPath and call s.callTTBFunc. // // An Options is returned only if multiple comparers or transformers // can apply simultaneously and will only contain values of those types // or sub-Options containing values of those types. filter(s *state, t reflect.Type, vx, vy reflect.Value) applicableOption } // applicableOption represents the following types: // // Fundamental: ignore | validator | *comparer | *transformer // Grouping: Options type applicableOption interface { Option // apply executes the option, which may mutate s or panic. apply(s *state, vx, vy reflect.Value) } // coreOption represents the following types: // // Fundamental: ignore | validator | *comparer | *transformer // Filters: *pathFilter | *valuesFilter type coreOption interface { Option isCore() } type core struct{} func (core) isCore() {} // Options is a list of [Option] values that also satisfies the [Option] interface. // Helper comparison packages may return an Options value when packing multiple // [Option] values into a single [Option]. When this package processes an Options, // it will be implicitly expanded into a flat list. // // Applying a filter on an Options is equivalent to applying that same filter // on all individual options held within. type Options []Option func (opts Options) filter(s *state, t reflect.Type, vx, vy reflect.Value) (out applicableOption) { for _, opt := range opts { switch opt := opt.filter(s, t, vx, vy); opt.(type) { case ignore: return ignore{} // Only ignore can short-circuit evaluation case validator: out = validator{} // Takes precedence over comparer or transformer case *comparer, *transformer, Options: switch out.(type) { case nil: out = opt case validator: // Keep validator case *comparer, *transformer, Options: out = Options{out, opt} // Conflicting comparers or transformers } } } return out } func (opts Options) apply(s *state, _, _ reflect.Value) { const warning = "ambiguous set of applicable options" const help = "consider using filters to ensure at most one Comparer or Transformer may apply" var ss []string for _, opt := range flattenOptions(nil, opts) { ss = append(ss, fmt.Sprint(opt)) } set := strings.Join(ss, "\n\t") panic(fmt.Sprintf("%s at %#v:\n\t%s\n%s", warning, s.curPath, set, help)) } func (opts Options) String() string { var ss []string for _, opt := range opts { ss = append(ss, fmt.Sprint(opt)) } return fmt.Sprintf("Options{%s}", strings.Join(ss, ", ")) } // FilterPath returns a new [Option] where opt is only evaluated if filter f // returns true for the current [Path] in the value tree. // // This filter is called even if a slice element or map entry is missing and // provides an opportunity to ignore such cases. The filter function must be // symmetric such that the filter result is identical regardless of whether the // missing value is from x or y. // // The option passed in may be an [Ignore], [Transformer], [Comparer], [Options], or // a previously filtered [Option]. func FilterPath(f func(Path) bool, opt Option) Option { if f == nil { panic("invalid path filter function") } if opt := normalizeOption(opt); opt != nil { return &pathFilter{fnc: f, opt: opt} } return nil } type pathFilter struct { core fnc func(Path) bool opt Option } func (f pathFilter) filter(s *state, t reflect.Type, vx, vy reflect.Value) applicableOption { if f.fnc(s.curPath) { return f.opt.filter(s, t, vx, vy) } return nil } func (f pathFilter) String() string { return fmt.Sprintf("FilterPath(%s, %v)", function.NameOf(reflect.ValueOf(f.fnc)), f.opt) } // FilterValues returns a new [Option] where opt is only evaluated if filter f, // which is a function of the form "func(T, T) bool", returns true for the // current pair of values being compared. If either value is invalid or // the type of the values is not assignable to T, then this filter implicitly // returns false. // // The filter function must be // symmetric (i.e., agnostic to the order of the inputs) and // deterministic (i.e., produces the same result when given the same inputs). // If T is an interface, it is possible that f is called with two values with // different concrete types that both implement T. // // The option passed in may be an [Ignore], [Transformer], [Comparer], [Options], or // a previously filtered [Option]. func FilterValues(f interface{}, opt Option) Option { v := reflect.ValueOf(f) if !function.IsType(v.Type(), function.ValueFilter) || v.IsNil() { panic(fmt.Sprintf("invalid values filter function: %T", f)) } if opt := normalizeOption(opt); opt != nil { vf := &valuesFilter{fnc: v, opt: opt} if ti := v.Type().In(0); ti.Kind() != reflect.Interface || ti.NumMethod() > 0 { vf.typ = ti } return vf } return nil } type valuesFilter struct { core typ reflect.Type // T fnc reflect.Value // func(T, T) bool opt Option } func (f valuesFilter) filter(s *state, t reflect.Type, vx, vy reflect.Value) applicableOption { if !vx.IsValid() || !vx.CanInterface() || !vy.IsValid() || !vy.CanInterface() { return nil } if (f.typ == nil || t.AssignableTo(f.typ)) && s.callTTBFunc(f.fnc, vx, vy) { return f.opt.filter(s, t, vx, vy) } return nil } func (f valuesFilter) String() string { return fmt.Sprintf("FilterValues(%s, %v)", function.NameOf(f.fnc), f.opt) } // Ignore is an [Option] that causes all comparisons to be ignored. // This value is intended to be combined with [FilterPath] or [FilterValues]. // It is an error to pass an unfiltered Ignore option to [Equal]. func Ignore() Option { return ignore{} } type ignore struct{ core } func (ignore) isFiltered() bool { return false } func (ignore) filter(_ *state, _ reflect.Type, _, _ reflect.Value) applicableOption { return ignore{} } func (ignore) apply(s *state, _, _ reflect.Value) { s.report(true, reportByIgnore) } func (ignore) String() string { return "Ignore()" } // validator is a sentinel Option type to indicate that some options could not // be evaluated due to unexported fields, missing slice elements, or // missing map entries. Both values are validator only for unexported fields. type validator struct{ core } func (validator) filter(_ *state, _ reflect.Type, vx, vy reflect.Value) applicableOption { if !vx.IsValid() || !vy.IsValid() { return validator{} } if !vx.CanInterface() || !vy.CanInterface() { return validator{} } return nil } func (validator) apply(s *state, vx, vy reflect.Value) { // Implies missing slice element or map entry. if !vx.IsValid() || !vy.IsValid() { s.report(vx.IsValid() == vy.IsValid(), 0) return } // Unable to Interface implies unexported field without visibility access. if !vx.CanInterface() || !vy.CanInterface() { help := "consider using a custom Comparer; if you control the implementation of type, you can also consider using an Exporter, AllowUnexported, or cmpopts.IgnoreUnexported" var name string if t := s.curPath.Index(-2).Type(); t.Name() != "" { // Named type with unexported fields. name = fmt.Sprintf("%q.%v", t.PkgPath(), t.Name()) // e.g., "path/to/package".MyType isProtoMessage := func(t reflect.Type) bool { m, ok := reflect.PointerTo(t).MethodByName("ProtoReflect") return ok && m.Type.NumIn() == 1 && m.Type.NumOut() == 1 && m.Type.Out(0).PkgPath() == "google.golang.org/protobuf/reflect/protoreflect" && m.Type.Out(0).Name() == "Message" } if isProtoMessage(t) { help = `consider using "google.golang.org/protobuf/testing/protocmp".Transform to compare proto.Message types` } else if _, ok := reflect.New(t).Interface().(error); ok { help = "consider using cmpopts.EquateErrors to compare error values" } else if t.Comparable() { help = "consider using cmpopts.EquateComparable to compare comparable Go types" } } else { // Unnamed type with unexported fields. Derive PkgPath from field. var pkgPath string for i := 0; i < t.NumField() && pkgPath == ""; i++ { pkgPath = t.Field(i).PkgPath } name = fmt.Sprintf("%q.(%v)", pkgPath, t.String()) // e.g., "path/to/package".(struct { a int }) } panic(fmt.Sprintf("cannot handle unexported field at %#v:\n\t%v\n%s", s.curPath, name, help)) } panic("not reachable") } // identRx represents a valid identifier according to the Go specification. const identRx = `[_\p{L}][_\p{L}\p{N}]*` var identsRx = regexp.MustCompile(`^` + identRx + `(\.` + identRx + `)*$`) // Transformer returns an [Option] that applies a transformation function that // converts values of a certain type into that of another. // // The transformer f must be a function "func(T) R" that converts values of // type T to those of type R and is implicitly filtered to input values // assignable to T. The transformer must not mutate T in any way. // // To help prevent some cases of infinite recursive cycles applying the // same transform to the output of itself (e.g., in the case where the // input and output types are the same), an implicit filter is added such that // a transformer is applicable only if that exact transformer is not already // in the tail of the [Path] since the last non-[Transform] step. // For situations where the implicit filter is still insufficient, // consider using [github.com/google/go-cmp/cmp/cmpopts.AcyclicTransformer], // which adds a filter to prevent the transformer from // being recursively applied upon itself. // // The name is a user provided label that is used as the [Transform.Name] in the // transformation [PathStep] (and eventually shown in the [Diff] output). // The name must be a valid identifier or qualified identifier in Go syntax. // If empty, an arbitrary name is used. func Transformer(name string, f interface{}) Option { v := reflect.ValueOf(f) if !function.IsType(v.Type(), function.Transformer) || v.IsNil() { panic(fmt.Sprintf("invalid transformer function: %T", f)) } if name == "" { name = function.NameOf(v) if !identsRx.MatchString(name) { name = "λ" // Lambda-symbol as placeholder name } } else if !identsRx.MatchString(name) { panic(fmt.Sprintf("invalid name: %q", name)) } tr := &transformer{name: name, fnc: reflect.ValueOf(f)} if ti := v.Type().In(0); ti.Kind() != reflect.Interface || ti.NumMethod() > 0 { tr.typ = ti } return tr } type transformer struct { core name string typ reflect.Type // T fnc reflect.Value // func(T) R } func (tr *transformer) isFiltered() bool { return tr.typ != nil } func (tr *transformer) filter(s *state, t reflect.Type, _, _ reflect.Value) applicableOption { for i := len(s.curPath) - 1; i >= 0; i-- { if t, ok := s.curPath[i].(Transform); !ok { break // Hit most recent non-Transform step } else if tr == t.trans { return nil // Cannot directly use same Transform } } if tr.typ == nil || t.AssignableTo(tr.typ) { return tr } return nil } func (tr *transformer) apply(s *state, vx, vy reflect.Value) { step := Transform{&transform{pathStep{typ: tr.fnc.Type().Out(0)}, tr}} vvx := s.callTRFunc(tr.fnc, vx, step) vvy := s.callTRFunc(tr.fnc, vy, step) step.vx, step.vy = vvx, vvy s.compareAny(step) } func (tr transformer) String() string { return fmt.Sprintf("Transformer(%s, %s)", tr.name, function.NameOf(tr.fnc)) } // Comparer returns an [Option] that determines whether two values are equal // to each other. // // The comparer f must be a function "func(T, T) bool" and is implicitly // filtered to input values assignable to T. If T is an interface, it is // possible that f is called with two values of different concrete types that // both implement T. // // The equality function must be: // - Symmetric: equal(x, y) == equal(y, x) // - Deterministic: equal(x, y) == equal(x, y) // - Pure: equal(x, y) does not modify x or y func Comparer(f interface{}) Option { v := reflect.ValueOf(f) if !function.IsType(v.Type(), function.Equal) || v.IsNil() { panic(fmt.Sprintf("invalid comparer function: %T", f)) } cm := &comparer{fnc: v} if ti := v.Type().In(0); ti.Kind() != reflect.Interface || ti.NumMethod() > 0 { cm.typ = ti } return cm } type comparer struct { core typ reflect.Type // T fnc reflect.Value // func(T, T) bool } func (cm *comparer) isFiltered() bool { return cm.typ != nil } func (cm *comparer) filter(_ *state, t reflect.Type, _, _ reflect.Value) applicableOption { if cm.typ == nil || t.AssignableTo(cm.typ) { return cm } return nil } func (cm *comparer) apply(s *state, vx, vy reflect.Value) { eq := s.callTTBFunc(cm.fnc, vx, vy) s.report(eq, reportByFunc) } func (cm comparer) String() string { return fmt.Sprintf("Comparer(%s)", function.NameOf(cm.fnc)) } // Exporter returns an [Option] that specifies whether [Equal] is allowed to // introspect into the unexported fields of certain struct types. // // Users of this option must understand that comparing on unexported fields // from external packages is not safe since changes in the internal // implementation of some external package may cause the result of [Equal] // to unexpectedly change. However, it may be valid to use this option on types // defined in an internal package where the semantic meaning of an unexported // field is in the control of the user. // // In many cases, a custom [Comparer] should be used instead that defines // equality as a function of the public API of a type rather than the underlying // unexported implementation. // // For example, the [reflect.Type] documentation defines equality to be determined // by the == operator on the interface (essentially performing a shallow pointer // comparison) and most attempts to compare *[regexp.Regexp] types are interested // in only checking that the regular expression strings are equal. // Both of these are accomplished using [Comparer] options: // // Comparer(func(x, y reflect.Type) bool { return x == y }) // Comparer(func(x, y *regexp.Regexp) bool { return x.String() == y.String() }) // // In other cases, the [github.com/google/go-cmp/cmp/cmpopts.IgnoreUnexported] // option can be used to ignore all unexported fields on specified struct types. func Exporter(f func(reflect.Type) bool) Option { return exporter(f) } type exporter func(reflect.Type) bool func (exporter) filter(_ *state, _ reflect.Type, _, _ reflect.Value) applicableOption { panic("not implemented") } // AllowUnexported returns an [Option] that allows [Equal] to forcibly introspect // unexported fields of the specified struct types. // // See [Exporter] for the proper use of this option. func AllowUnexported(types ...interface{}) Option { m := make(map[reflect.Type]bool) for _, typ := range types { t := reflect.TypeOf(typ) if t.Kind() != reflect.Struct { panic(fmt.Sprintf("invalid struct type: %T", typ)) } m[t] = true } return exporter(func(t reflect.Type) bool { return m[t] }) } // Result represents the comparison result for a single node and // is provided by cmp when calling Report (see [Reporter]). type Result struct { _ [0]func() // Make Result incomparable flags resultFlags } // Equal reports whether the node was determined to be equal or not. // As a special case, ignored nodes are considered equal. func (r Result) Equal() bool { return r.flags&(reportEqual|reportByIgnore) != 0 } // ByIgnore reports whether the node is equal because it was ignored. // This never reports true if [Result.Equal] reports false. func (r Result) ByIgnore() bool { return r.flags&reportByIgnore != 0 } // ByMethod reports whether the Equal method determined equality. func (r Result) ByMethod() bool { return r.flags&reportByMethod != 0 } // ByFunc reports whether a [Comparer] function determined equality. func (r Result) ByFunc() bool { return r.flags&reportByFunc != 0 } // ByCycle reports whether a reference cycle was detected. func (r Result) ByCycle() bool { return r.flags&reportByCycle != 0 } type resultFlags uint const ( _ resultFlags = (1 << iota) / 2 reportEqual reportUnequal reportByIgnore reportByMethod reportByFunc reportByCycle ) // Reporter is an [Option] that can be passed to [Equal]. When [Equal] traverses // the value trees, it calls PushStep as it descends into each node in the // tree and PopStep as it ascend out of the node. The leaves of the tree are // either compared (determined to be equal or not equal) or ignored and reported // as such by calling the Report method. func Reporter(r interface { // PushStep is called when a tree-traversal operation is performed. // The PathStep itself is only valid until the step is popped. // The PathStep.Values are valid for the duration of the entire traversal // and must not be mutated. // // Equal always calls PushStep at the start to provide an operation-less // PathStep used to report the root values. // // Within a slice, the exact set of inserted, removed, or modified elements // is unspecified and may change in future implementations. // The entries of a map are iterated through in an unspecified order. PushStep(PathStep) // Report is called exactly once on leaf nodes to report whether the // comparison identified the node as equal, unequal, or ignored. // A leaf node is one that is immediately preceded by and followed by // a pair of PushStep and PopStep calls. Report(Result) // PopStep ascends back up the value tree. // There is always a matching pop call for every push call. PopStep() }) Option { return reporter{r} } type reporter struct{ reporterIface } type reporterIface interface { PushStep(PathStep) Report(Result) PopStep() } func (reporter) filter(_ *state, _ reflect.Type, _, _ reflect.Value) applicableOption { panic("not implemented") } // normalizeOption normalizes the input options such that all Options groups // are flattened and groups with a single element are reduced to that element. // Only coreOptions and Options containing coreOptions are allowed. func normalizeOption(src Option) Option { switch opts := flattenOptions(nil, Options{src}); len(opts) { case 0: return nil case 1: return opts[0] default: return opts } } // flattenOptions copies all options in src to dst as a flat list. // Only coreOptions and Options containing coreOptions are allowed. func flattenOptions(dst, src Options) Options { for _, opt := range src { switch opt := opt.(type) { case nil: continue case Options: dst = flattenOptions(dst, opt) case coreOption: dst = append(dst, opt) default: panic(fmt.Sprintf("invalid option type: %T", opt)) } } return dst }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/go-cmp/cmp/export.go
vendor/github.com/google/go-cmp/cmp/export.go
// Copyright 2017, 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 cmp import ( "reflect" "unsafe" ) // retrieveUnexportedField uses unsafe to forcibly retrieve any field from // a struct such that the value has read-write permissions. // // The parent struct, v, must be addressable, while f must be a StructField // describing the field to retrieve. If addr is false, // then the returned value will be shallowed copied to be non-addressable. func retrieveUnexportedField(v reflect.Value, f reflect.StructField, addr bool) reflect.Value { ve := reflect.NewAt(f.Type, unsafe.Pointer(uintptr(unsafe.Pointer(v.UnsafeAddr()))+f.Offset)).Elem() if !addr { // A field is addressable if and only if the struct is addressable. // If the original parent value was not addressable, shallow copy the // value to make it non-addressable to avoid leaking an implementation // detail of how forcibly exporting a field works. if ve.Kind() == reflect.Interface && ve.IsNil() { return reflect.Zero(f.Type) } return reflect.ValueOf(ve.Interface()).Convert(f.Type) } return ve }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/go-cmp/cmp/report.go
vendor/github.com/google/go-cmp/cmp/report.go
// Copyright 2017, 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 cmp // defaultReporter implements the reporter interface. // // As Equal serially calls the PushStep, Report, and PopStep methods, the // defaultReporter constructs a tree-based representation of the compared value // and the result of each comparison (see valueNode). // // When the String method is called, the FormatDiff method transforms the // valueNode tree into a textNode tree, which is a tree-based representation // of the textual output (see textNode). // // Lastly, the textNode.String method produces the final report as a string. type defaultReporter struct { root *valueNode curr *valueNode } func (r *defaultReporter) PushStep(ps PathStep) { r.curr = r.curr.PushStep(ps) if r.root == nil { r.root = r.curr } } func (r *defaultReporter) Report(rs Result) { r.curr.Report(rs) } func (r *defaultReporter) PopStep() { r.curr = r.curr.PopStep() } // String provides a full report of the differences detected as a structured // literal in pseudo-Go syntax. String may only be called after the entire tree // has been traversed. func (r *defaultReporter) String() string { assert(r.root != nil && r.curr == nil) if r.root.NumDiff == 0 { return "" } ptrs := new(pointerReferences) text := formatOptions{}.FormatDiff(r.root, ptrs) resolveReferences(text) return text.String() } func assert(ok bool) { if !ok { panic("assertion failure") } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/go-cmp/cmp/internal/flags/flags.go
vendor/github.com/google/go-cmp/cmp/internal/flags/flags.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 flags // Deterministic controls whether the output of Diff should be deterministic. // This is only used for testing. var Deterministic bool
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/go-cmp/cmp/internal/diff/debug_disable.go
vendor/github.com/google/go-cmp/cmp/internal/diff/debug_disable.go
// Copyright 2017, The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build !cmp_debug // +build !cmp_debug package diff var debug debugger type debugger struct{} func (debugger) Begin(_, _ int, f EqualFunc, _, _ *EditScript) EqualFunc { return f } func (debugger) Update() {} func (debugger) Finish() {}
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/go-cmp/cmp/internal/diff/debug_enable.go
vendor/github.com/google/go-cmp/cmp/internal/diff/debug_enable.go
// Copyright 2017, The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build cmp_debug // +build cmp_debug package diff import ( "fmt" "strings" "sync" "time" ) // The algorithm can be seen running in real-time by enabling debugging: // go test -tags=cmp_debug -v // // Example output: // === RUN TestDifference/#34 // ┌───────────────────────────────┐ // │ \ · · · · · · · · · · · · · · │ // │ · # · · · · · · · · · · · · · │ // │ · \ · · · · · · · · · · · · · │ // │ · · \ · · · · · · · · · · · · │ // │ · · · X # · · · · · · · · · · │ // │ · · · # \ · · · · · · · · · · │ // │ · · · · · # # · · · · · · · · │ // │ · · · · · # \ · · · · · · · · │ // │ · · · · · · · \ · · · · · · · │ // │ · · · · · · · · \ · · · · · · │ // │ · · · · · · · · · \ · · · · · │ // │ · · · · · · · · · · \ · · # · │ // │ · · · · · · · · · · · \ # # · │ // │ · · · · · · · · · · · # # # · │ // │ · · · · · · · · · · # # # # · │ // │ · · · · · · · · · # # # # # · │ // │ · · · · · · · · · · · · · · \ │ // └───────────────────────────────┘ // [.Y..M.XY......YXYXY.|] // // The grid represents the edit-graph where the horizontal axis represents // list X and the vertical axis represents list Y. The start of the two lists // is the top-left, while the ends are the bottom-right. The '·' represents // an unexplored node in the graph. The '\' indicates that the two symbols // from list X and Y are equal. The 'X' indicates that two symbols are similar // (but not exactly equal) to each other. The '#' indicates that the two symbols // are different (and not similar). The algorithm traverses this graph trying to // make the paths starting in the top-left and the bottom-right connect. // // The series of '.', 'X', 'Y', and 'M' characters at the bottom represents // the currently established path from the forward and reverse searches, // separated by a '|' character. const ( updateDelay = 100 * time.Millisecond finishDelay = 500 * time.Millisecond ansiTerminal = true // ANSI escape codes used to move terminal cursor ) var debug debugger type debugger struct { sync.Mutex p1, p2 EditScript fwdPath, revPath *EditScript grid []byte lines int } func (dbg *debugger) Begin(nx, ny int, f EqualFunc, p1, p2 *EditScript) EqualFunc { dbg.Lock() dbg.fwdPath, dbg.revPath = p1, p2 top := "┌─" + strings.Repeat("──", nx) + "┐\n" row := "│ " + strings.Repeat("· ", nx) + "│\n" btm := "└─" + strings.Repeat("──", nx) + "┘\n" dbg.grid = []byte(top + strings.Repeat(row, ny) + btm) dbg.lines = strings.Count(dbg.String(), "\n") fmt.Print(dbg) // Wrap the EqualFunc so that we can intercept each result. return func(ix, iy int) (r Result) { cell := dbg.grid[len(top)+iy*len(row):][len("│ ")+len("· ")*ix:][:len("·")] for i := range cell { cell[i] = 0 // Zero out the multiple bytes of UTF-8 middle-dot } switch r = f(ix, iy); { case r.Equal(): cell[0] = '\\' case r.Similar(): cell[0] = 'X' default: cell[0] = '#' } return } } func (dbg *debugger) Update() { dbg.print(updateDelay) } func (dbg *debugger) Finish() { dbg.print(finishDelay) dbg.Unlock() } func (dbg *debugger) String() string { dbg.p1, dbg.p2 = *dbg.fwdPath, dbg.p2[:0] for i := len(*dbg.revPath) - 1; i >= 0; i-- { dbg.p2 = append(dbg.p2, (*dbg.revPath)[i]) } return fmt.Sprintf("%s[%v|%v]\n\n", dbg.grid, dbg.p1, dbg.p2) } func (dbg *debugger) print(d time.Duration) { if ansiTerminal { fmt.Printf("\x1b[%dA", dbg.lines) // Reset terminal cursor } fmt.Print(dbg) time.Sleep(d) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/go-cmp/cmp/internal/diff/diff.go
vendor/github.com/google/go-cmp/cmp/internal/diff/diff.go
// Copyright 2017, 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 diff implements an algorithm for producing edit-scripts. // The edit-script is a sequence of operations needed to transform one list // of symbols into another (or vice-versa). The edits allowed are insertions, // deletions, and modifications. The summation of all edits is called the // Levenshtein distance as this problem is well-known in computer science. // // This package prioritizes performance over accuracy. That is, the run time // is more important than obtaining a minimal Levenshtein distance. package diff import ( "math/rand" "time" "github.com/google/go-cmp/cmp/internal/flags" ) // EditType represents a single operation within an edit-script. type EditType uint8 const ( // Identity indicates that a symbol pair is identical in both list X and Y. Identity EditType = iota // UniqueX indicates that a symbol only exists in X and not Y. UniqueX // UniqueY indicates that a symbol only exists in Y and not X. UniqueY // Modified indicates that a symbol pair is a modification of each other. Modified ) // EditScript represents the series of differences between two lists. type EditScript []EditType // String returns a human-readable string representing the edit-script where // Identity, UniqueX, UniqueY, and Modified are represented by the // '.', 'X', 'Y', and 'M' characters, respectively. func (es EditScript) String() string { b := make([]byte, len(es)) for i, e := range es { switch e { case Identity: b[i] = '.' case UniqueX: b[i] = 'X' case UniqueY: b[i] = 'Y' case Modified: b[i] = 'M' default: panic("invalid edit-type") } } return string(b) } // stats returns a histogram of the number of each type of edit operation. func (es EditScript) stats() (s struct{ NI, NX, NY, NM int }) { for _, e := range es { switch e { case Identity: s.NI++ case UniqueX: s.NX++ case UniqueY: s.NY++ case Modified: s.NM++ default: panic("invalid edit-type") } } return } // Dist is the Levenshtein distance and is guaranteed to be 0 if and only if // lists X and Y are equal. func (es EditScript) Dist() int { return len(es) - es.stats().NI } // LenX is the length of the X list. func (es EditScript) LenX() int { return len(es) - es.stats().NY } // LenY is the length of the Y list. func (es EditScript) LenY() int { return len(es) - es.stats().NX } // EqualFunc reports whether the symbols at indexes ix and iy are equal. // When called by Difference, the index is guaranteed to be within nx and ny. type EqualFunc func(ix int, iy int) Result // Result is the result of comparison. // NumSame is the number of sub-elements that are equal. // NumDiff is the number of sub-elements that are not equal. type Result struct{ NumSame, NumDiff int } // BoolResult returns a Result that is either Equal or not Equal. func BoolResult(b bool) Result { if b { return Result{NumSame: 1} // Equal, Similar } else { return Result{NumDiff: 2} // Not Equal, not Similar } } // Equal indicates whether the symbols are equal. Two symbols are equal // if and only if NumDiff == 0. If Equal, then they are also Similar. func (r Result) Equal() bool { return r.NumDiff == 0 } // Similar indicates whether two symbols are similar and may be represented // by using the Modified type. As a special case, we consider binary comparisons // (i.e., those that return Result{1, 0} or Result{0, 1}) to be similar. // // The exact ratio of NumSame to NumDiff to determine similarity may change. func (r Result) Similar() bool { // Use NumSame+1 to offset NumSame so that binary comparisons are similar. return r.NumSame+1 >= r.NumDiff } var randBool = rand.New(rand.NewSource(time.Now().Unix())).Intn(2) == 0 // Difference reports whether two lists of lengths nx and ny are equal // given the definition of equality provided as f. // // This function returns an edit-script, which is a sequence of operations // needed to convert one list into the other. The following invariants for // the edit-script are maintained: // - eq == (es.Dist()==0) // - nx == es.LenX() // - ny == es.LenY() // // This algorithm is not guaranteed to be an optimal solution (i.e., one that // produces an edit-script with a minimal Levenshtein distance). This algorithm // favors performance over optimality. The exact output is not guaranteed to // be stable and may change over time. func Difference(nx, ny int, f EqualFunc) (es EditScript) { // This algorithm is based on traversing what is known as an "edit-graph". // See Figure 1 from "An O(ND) Difference Algorithm and Its Variations" // by Eugene W. Myers. Since D can be as large as N itself, this is // effectively O(N^2). Unlike the algorithm from that paper, we are not // interested in the optimal path, but at least some "decent" path. // // For example, let X and Y be lists of symbols: // X = [A B C A B B A] // Y = [C B A B A C] // // The edit-graph can be drawn as the following: // A B C A B B A // ┌─────────────┐ // C │_|_|\|_|_|_|_│ 0 // B │_|\|_|_|\|\|_│ 1 // A │\|_|_|\|_|_|\│ 2 // B │_|\|_|_|\|\|_│ 3 // A │\|_|_|\|_|_|\│ 4 // C │ | |\| | | | │ 5 // └─────────────┘ 6 // 0 1 2 3 4 5 6 7 // // List X is written along the horizontal axis, while list Y is written // along the vertical axis. At any point on this grid, if the symbol in // list X matches the corresponding symbol in list Y, then a '\' is drawn. // The goal of any minimal edit-script algorithm is to find a path from the // top-left corner to the bottom-right corner, while traveling through the // fewest horizontal or vertical edges. // A horizontal edge is equivalent to inserting a symbol from list X. // A vertical edge is equivalent to inserting a symbol from list Y. // A diagonal edge is equivalent to a matching symbol between both X and Y. // Invariants: // - 0 ≤ fwdPath.X ≤ (fwdFrontier.X, revFrontier.X) ≤ revPath.X ≤ nx // - 0 ≤ fwdPath.Y ≤ (fwdFrontier.Y, revFrontier.Y) ≤ revPath.Y ≤ ny // // In general: // - fwdFrontier.X < revFrontier.X // - fwdFrontier.Y < revFrontier.Y // // Unless, it is time for the algorithm to terminate. fwdPath := path{+1, point{0, 0}, make(EditScript, 0, (nx+ny)/2)} revPath := path{-1, point{nx, ny}, make(EditScript, 0)} fwdFrontier := fwdPath.point // Forward search frontier revFrontier := revPath.point // Reverse search frontier // Search budget bounds the cost of searching for better paths. // The longest sequence of non-matching symbols that can be tolerated is // approximately the square-root of the search budget. searchBudget := 4 * (nx + ny) // O(n) // Running the tests with the "cmp_debug" build tag prints a visualization // of the algorithm running in real-time. This is educational for // understanding how the algorithm works. See debug_enable.go. f = debug.Begin(nx, ny, f, &fwdPath.es, &revPath.es) // The algorithm below is a greedy, meet-in-the-middle algorithm for // computing sub-optimal edit-scripts between two lists. // // The algorithm is approximately as follows: // - Searching for differences switches back-and-forth between // a search that starts at the beginning (the top-left corner), and // a search that starts at the end (the bottom-right corner). // The goal of the search is connect with the search // from the opposite corner. // - As we search, we build a path in a greedy manner, // where the first match seen is added to the path (this is sub-optimal, // but provides a decent result in practice). When matches are found, // we try the next pair of symbols in the lists and follow all matches // as far as possible. // - When searching for matches, we search along a diagonal going through // through the "frontier" point. If no matches are found, // we advance the frontier towards the opposite corner. // - This algorithm terminates when either the X coordinates or the // Y coordinates of the forward and reverse frontier points ever intersect. // This algorithm is correct even if searching only in the forward direction // or in the reverse direction. We do both because it is commonly observed // that two lists commonly differ because elements were added to the front // or end of the other list. // // Non-deterministically start with either the forward or reverse direction // to introduce some deliberate instability so that we have the flexibility // to change this algorithm in the future. if flags.Deterministic || randBool { goto forwardSearch } else { goto reverseSearch } forwardSearch: { // Forward search from the beginning. if fwdFrontier.X >= revFrontier.X || fwdFrontier.Y >= revFrontier.Y || searchBudget == 0 { goto finishSearch } for stop1, stop2, i := false, false, 0; !(stop1 && stop2) && searchBudget > 0; i++ { // Search in a diagonal pattern for a match. z := zigzag(i) p := point{fwdFrontier.X + z, fwdFrontier.Y - z} switch { case p.X >= revPath.X || p.Y < fwdPath.Y: stop1 = true // Hit top-right corner case p.Y >= revPath.Y || p.X < fwdPath.X: stop2 = true // Hit bottom-left corner case f(p.X, p.Y).Equal(): // Match found, so connect the path to this point. fwdPath.connect(p, f) fwdPath.append(Identity) // Follow sequence of matches as far as possible. for fwdPath.X < revPath.X && fwdPath.Y < revPath.Y { if !f(fwdPath.X, fwdPath.Y).Equal() { break } fwdPath.append(Identity) } fwdFrontier = fwdPath.point stop1, stop2 = true, true default: searchBudget-- // Match not found } debug.Update() } // Advance the frontier towards reverse point. if revPath.X-fwdFrontier.X >= revPath.Y-fwdFrontier.Y { fwdFrontier.X++ } else { fwdFrontier.Y++ } goto reverseSearch } reverseSearch: { // Reverse search from the end. if fwdFrontier.X >= revFrontier.X || fwdFrontier.Y >= revFrontier.Y || searchBudget == 0 { goto finishSearch } for stop1, stop2, i := false, false, 0; !(stop1 && stop2) && searchBudget > 0; i++ { // Search in a diagonal pattern for a match. z := zigzag(i) p := point{revFrontier.X - z, revFrontier.Y + z} switch { case fwdPath.X >= p.X || revPath.Y < p.Y: stop1 = true // Hit bottom-left corner case fwdPath.Y >= p.Y || revPath.X < p.X: stop2 = true // Hit top-right corner case f(p.X-1, p.Y-1).Equal(): // Match found, so connect the path to this point. revPath.connect(p, f) revPath.append(Identity) // Follow sequence of matches as far as possible. for fwdPath.X < revPath.X && fwdPath.Y < revPath.Y { if !f(revPath.X-1, revPath.Y-1).Equal() { break } revPath.append(Identity) } revFrontier = revPath.point stop1, stop2 = true, true default: searchBudget-- // Match not found } debug.Update() } // Advance the frontier towards forward point. if revFrontier.X-fwdPath.X >= revFrontier.Y-fwdPath.Y { revFrontier.X-- } else { revFrontier.Y-- } goto forwardSearch } finishSearch: // Join the forward and reverse paths and then append the reverse path. fwdPath.connect(revPath.point, f) for i := len(revPath.es) - 1; i >= 0; i-- { t := revPath.es[i] revPath.es = revPath.es[:i] fwdPath.append(t) } debug.Finish() return fwdPath.es } type path struct { dir int // +1 if forward, -1 if reverse point // Leading point of the EditScript path es EditScript } // connect appends any necessary Identity, Modified, UniqueX, or UniqueY types // to the edit-script to connect p.point to dst. func (p *path) connect(dst point, f EqualFunc) { if p.dir > 0 { // Connect in forward direction. for dst.X > p.X && dst.Y > p.Y { switch r := f(p.X, p.Y); { case r.Equal(): p.append(Identity) case r.Similar(): p.append(Modified) case dst.X-p.X >= dst.Y-p.Y: p.append(UniqueX) default: p.append(UniqueY) } } for dst.X > p.X { p.append(UniqueX) } for dst.Y > p.Y { p.append(UniqueY) } } else { // Connect in reverse direction. for p.X > dst.X && p.Y > dst.Y { switch r := f(p.X-1, p.Y-1); { case r.Equal(): p.append(Identity) case r.Similar(): p.append(Modified) case p.Y-dst.Y >= p.X-dst.X: p.append(UniqueY) default: p.append(UniqueX) } } for p.X > dst.X { p.append(UniqueX) } for p.Y > dst.Y { p.append(UniqueY) } } } func (p *path) append(t EditType) { p.es = append(p.es, t) switch t { case Identity, Modified: p.add(p.dir, p.dir) case UniqueX: p.add(p.dir, 0) case UniqueY: p.add(0, p.dir) } debug.Update() } type point struct{ X, Y int } func (p *point) add(dx, dy int) { p.X += dx; p.Y += dy } // zigzag maps a consecutive sequence of integers to a zig-zag sequence. // // [0 1 2 3 4 5 ...] => [0 -1 +1 -2 +2 ...] func zigzag(x int) int { if x&1 != 0 { x = ^x } return x >> 1 }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/go-cmp/cmp/internal/value/sort.go
vendor/github.com/google/go-cmp/cmp/internal/value/sort.go
// Copyright 2017, 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 value import ( "fmt" "math" "reflect" "sort" ) // SortKeys sorts a list of map keys, deduplicating keys if necessary. // The type of each value must be comparable. func SortKeys(vs []reflect.Value) []reflect.Value { if len(vs) == 0 { return vs } // Sort the map keys. sort.SliceStable(vs, func(i, j int) bool { return isLess(vs[i], vs[j]) }) // Deduplicate keys (fails for NaNs). vs2 := vs[:1] for _, v := range vs[1:] { if isLess(vs2[len(vs2)-1], v) { vs2 = append(vs2, v) } } return vs2 } // isLess is a generic function for sorting arbitrary map keys. // The inputs must be of the same type and must be comparable. func isLess(x, y reflect.Value) bool { switch x.Type().Kind() { case reflect.Bool: return !x.Bool() && y.Bool() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return x.Int() < y.Int() case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return x.Uint() < y.Uint() case reflect.Float32, reflect.Float64: // NOTE: This does not sort -0 as less than +0 // since Go maps treat -0 and +0 as equal keys. fx, fy := x.Float(), y.Float() return fx < fy || math.IsNaN(fx) && !math.IsNaN(fy) case reflect.Complex64, reflect.Complex128: cx, cy := x.Complex(), y.Complex() rx, ix, ry, iy := real(cx), imag(cx), real(cy), imag(cy) if rx == ry || (math.IsNaN(rx) && math.IsNaN(ry)) { return ix < iy || math.IsNaN(ix) && !math.IsNaN(iy) } return rx < ry || math.IsNaN(rx) && !math.IsNaN(ry) case reflect.Ptr, reflect.UnsafePointer, reflect.Chan: return x.Pointer() < y.Pointer() case reflect.String: return x.String() < y.String() case reflect.Array: for i := 0; i < x.Len(); i++ { if isLess(x.Index(i), y.Index(i)) { return true } if isLess(y.Index(i), x.Index(i)) { return false } } return false case reflect.Struct: for i := 0; i < x.NumField(); i++ { if isLess(x.Field(i), y.Field(i)) { return true } if isLess(y.Field(i), x.Field(i)) { return false } } return false case reflect.Interface: vx, vy := x.Elem(), y.Elem() if !vx.IsValid() || !vy.IsValid() { return !vx.IsValid() && vy.IsValid() } tx, ty := vx.Type(), vy.Type() if tx == ty { return isLess(x.Elem(), y.Elem()) } if tx.Kind() != ty.Kind() { return vx.Kind() < vy.Kind() } if tx.String() != ty.String() { return tx.String() < ty.String() } if tx.PkgPath() != ty.PkgPath() { return tx.PkgPath() < ty.PkgPath() } // This can happen in rare situations, so we fallback to just comparing // the unique pointer for a reflect.Type. This guarantees deterministic // ordering within a program, but it is obviously not stable. return reflect.ValueOf(vx.Type()).Pointer() < reflect.ValueOf(vy.Type()).Pointer() default: // Must be Func, Map, or Slice; which are not comparable. panic(fmt.Sprintf("%T is not comparable", x.Type())) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/go-cmp/cmp/internal/value/pointer.go
vendor/github.com/google/go-cmp/cmp/internal/value/pointer.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 value import ( "reflect" "unsafe" ) // Pointer is an opaque typed pointer and is guaranteed to be comparable. type Pointer struct { p unsafe.Pointer t reflect.Type } // PointerOf returns a Pointer from v, which must be a // reflect.Ptr, reflect.Slice, or reflect.Map. func PointerOf(v reflect.Value) Pointer { // The proper representation of a pointer is unsafe.Pointer, // which is necessary if the GC ever uses a moving collector. return Pointer{unsafe.Pointer(v.Pointer()), v.Type()} } // IsNil reports whether the pointer is nil. func (p Pointer) IsNil() bool { return p.p == nil } // Uintptr returns the pointer as a uintptr. func (p Pointer) Uintptr() uintptr { return uintptr(p.p) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/go-cmp/cmp/internal/value/name.go
vendor/github.com/google/go-cmp/cmp/internal/value/name.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 value import ( "reflect" "strconv" ) var anyType = reflect.TypeOf((*interface{})(nil)).Elem() // TypeString is nearly identical to reflect.Type.String, // but has an additional option to specify that full type names be used. func TypeString(t reflect.Type, qualified bool) string { return string(appendTypeName(nil, t, qualified, false)) } func appendTypeName(b []byte, t reflect.Type, qualified, elideFunc bool) []byte { // BUG: Go reflection provides no way to disambiguate two named types // of the same name and within the same package, // but declared within the namespace of different functions. // Use the "any" alias instead of "interface{}" for better readability. if t == anyType { return append(b, "any"...) } // Named type. if t.Name() != "" { if qualified && t.PkgPath() != "" { b = append(b, '"') b = append(b, t.PkgPath()...) b = append(b, '"') b = append(b, '.') b = append(b, t.Name()...) } else { b = append(b, t.String()...) } return b } // Unnamed type. switch k := t.Kind(); k { case reflect.Bool, reflect.String, reflect.UnsafePointer, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: b = append(b, k.String()...) case reflect.Chan: if t.ChanDir() == reflect.RecvDir { b = append(b, "<-"...) } b = append(b, "chan"...) if t.ChanDir() == reflect.SendDir { b = append(b, "<-"...) } b = append(b, ' ') b = appendTypeName(b, t.Elem(), qualified, false) case reflect.Func: if !elideFunc { b = append(b, "func"...) } b = append(b, '(') for i := 0; i < t.NumIn(); i++ { if i > 0 { b = append(b, ", "...) } if i == t.NumIn()-1 && t.IsVariadic() { b = append(b, "..."...) b = appendTypeName(b, t.In(i).Elem(), qualified, false) } else { b = appendTypeName(b, t.In(i), qualified, false) } } b = append(b, ')') switch t.NumOut() { case 0: // Do nothing case 1: b = append(b, ' ') b = appendTypeName(b, t.Out(0), qualified, false) default: b = append(b, " ("...) for i := 0; i < t.NumOut(); i++ { if i > 0 { b = append(b, ", "...) } b = appendTypeName(b, t.Out(i), qualified, false) } b = append(b, ')') } case reflect.Struct: b = append(b, "struct{ "...) for i := 0; i < t.NumField(); i++ { if i > 0 { b = append(b, "; "...) } sf := t.Field(i) if !sf.Anonymous { if qualified && sf.PkgPath != "" { b = append(b, '"') b = append(b, sf.PkgPath...) b = append(b, '"') b = append(b, '.') } b = append(b, sf.Name...) b = append(b, ' ') } b = appendTypeName(b, sf.Type, qualified, false) if sf.Tag != "" { b = append(b, ' ') b = strconv.AppendQuote(b, string(sf.Tag)) } } if b[len(b)-1] == ' ' { b = b[:len(b)-1] } else { b = append(b, ' ') } b = append(b, '}') case reflect.Slice, reflect.Array: b = append(b, '[') if k == reflect.Array { b = strconv.AppendUint(b, uint64(t.Len()), 10) } b = append(b, ']') b = appendTypeName(b, t.Elem(), qualified, false) case reflect.Map: b = append(b, "map["...) b = appendTypeName(b, t.Key(), qualified, false) b = append(b, ']') b = appendTypeName(b, t.Elem(), qualified, false) case reflect.Ptr: b = append(b, '*') b = appendTypeName(b, t.Elem(), qualified, false) case reflect.Interface: b = append(b, "interface{ "...) for i := 0; i < t.NumMethod(); i++ { if i > 0 { b = append(b, "; "...) } m := t.Method(i) if qualified && m.PkgPath != "" { b = append(b, '"') b = append(b, m.PkgPath...) b = append(b, '"') b = append(b, '.') } b = append(b, m.Name...) b = appendTypeName(b, m.Type, qualified, true) } if b[len(b)-1] == ' ' { b = b[:len(b)-1] } else { b = append(b, ' ') } b = append(b, '}') default: panic("invalid kind: " + k.String()) } return b }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/google/go-cmp/cmp/internal/function/func.go
vendor/github.com/google/go-cmp/cmp/internal/function/func.go
// Copyright 2017, 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 function provides functionality for identifying function types. package function import ( "reflect" "regexp" "runtime" "strings" ) type funcType int const ( _ funcType = iota tbFunc // func(T) bool ttbFunc // func(T, T) bool ttiFunc // func(T, T) int trbFunc // func(T, R) bool tibFunc // func(T, I) bool trFunc // func(T) R Equal = ttbFunc // func(T, T) bool EqualAssignable = tibFunc // func(T, I) bool; encapsulates func(T, T) bool Transformer = trFunc // func(T) R ValueFilter = ttbFunc // func(T, T) bool Less = ttbFunc // func(T, T) bool Compare = ttiFunc // func(T, T) int ValuePredicate = tbFunc // func(T) bool KeyValuePredicate = trbFunc // func(T, R) bool ) var boolType = reflect.TypeOf(true) var intType = reflect.TypeOf(0) // IsType reports whether the reflect.Type is of the specified function type. func IsType(t reflect.Type, ft funcType) bool { if t == nil || t.Kind() != reflect.Func || t.IsVariadic() { return false } ni, no := t.NumIn(), t.NumOut() switch ft { case tbFunc: // func(T) bool if ni == 1 && no == 1 && t.Out(0) == boolType { return true } case ttbFunc: // func(T, T) bool if ni == 2 && no == 1 && t.In(0) == t.In(1) && t.Out(0) == boolType { return true } case ttiFunc: // func(T, T) int if ni == 2 && no == 1 && t.In(0) == t.In(1) && t.Out(0) == intType { return true } case trbFunc: // func(T, R) bool if ni == 2 && no == 1 && t.Out(0) == boolType { return true } case tibFunc: // func(T, I) bool if ni == 2 && no == 1 && t.In(0).AssignableTo(t.In(1)) && t.Out(0) == boolType { return true } case trFunc: // func(T) R if ni == 1 && no == 1 { return true } } return false } var lastIdentRx = regexp.MustCompile(`[_\p{L}][_\p{L}\p{N}]*$`) // NameOf returns the name of the function value. func NameOf(v reflect.Value) string { fnc := runtime.FuncForPC(v.Pointer()) if fnc == nil { return "<unknown>" } fullName := fnc.Name() // e.g., "long/path/name/mypkg.(*MyType).(long/path/name/mypkg.myMethod)-fm" // Method closures have a "-fm" suffix. fullName = strings.TrimSuffix(fullName, "-fm") var name string for len(fullName) > 0 { inParen := strings.HasSuffix(fullName, ")") fullName = strings.TrimSuffix(fullName, ")") s := lastIdentRx.FindString(fullName) if s == "" { break } name = s + "." + name fullName = strings.TrimSuffix(fullName, s) if i := strings.LastIndexByte(fullName, '('); inParen && i >= 0 { fullName = fullName[:i] } fullName = strings.TrimSuffix(fullName, ".") } return strings.TrimSuffix(name, ".") }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/Masterminds/goutils/randomstringutils.go
vendor/github.com/Masterminds/goutils/randomstringutils.go
/* Copyright 2014 Alexander Okoli Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package goutils import ( "fmt" "math" "math/rand" "time" "unicode" ) // RANDOM provides the time-based seed used to generate random numbers var RANDOM = rand.New(rand.NewSource(time.Now().UnixNano())) /* RandomNonAlphaNumeric creates a random string whose length is the number of characters specified. Characters will be chosen from the set of all characters (ASCII/Unicode values between 0 to 2,147,483,647 (math.MaxInt32)). Parameter: count - the length of random string to create Returns: string - the random string error - an error stemming from an invalid parameter within underlying function, RandomSeed(...) */ func RandomNonAlphaNumeric(count int) (string, error) { return RandomAlphaNumericCustom(count, false, false) } /* RandomAscii creates a random string whose length is the number of characters specified. Characters will be chosen from the set of characters whose ASCII value is between 32 and 126 (inclusive). Parameter: count - the length of random string to create Returns: string - the random string error - an error stemming from an invalid parameter within underlying function, RandomSeed(...) */ func RandomAscii(count int) (string, error) { return Random(count, 32, 127, false, false) } /* RandomNumeric creates a random string whose length is the number of characters specified. Characters will be chosen from the set of numeric characters. Parameter: count - the length of random string to create Returns: string - the random string error - an error stemming from an invalid parameter within underlying function, RandomSeed(...) */ func RandomNumeric(count int) (string, error) { return Random(count, 0, 0, false, true) } /* RandomAlphabetic creates a random string whose length is the number of characters specified. Characters will be chosen from the set of alphabetic characters. Parameters: count - the length of random string to create Returns: string - the random string error - an error stemming from an invalid parameter within underlying function, RandomSeed(...) */ func RandomAlphabetic(count int) (string, error) { return Random(count, 0, 0, true, false) } /* RandomAlphaNumeric creates a random string whose length is the number of characters specified. Characters will be chosen from the set of alpha-numeric characters. Parameter: count - the length of random string to create Returns: string - the random string error - an error stemming from an invalid parameter within underlying function, RandomSeed(...) */ func RandomAlphaNumeric(count int) (string, error) { return Random(count, 0, 0, true, true) } /* RandomAlphaNumericCustom creates a random string whose length is the number of characters specified. Characters will be chosen from the set of alpha-numeric characters as indicated by the arguments. Parameters: count - the length of random string to create letters - if true, generated string may include alphabetic characters numbers - if true, generated string may include numeric characters Returns: string - the random string error - an error stemming from an invalid parameter within underlying function, RandomSeed(...) */ func RandomAlphaNumericCustom(count int, letters bool, numbers bool) (string, error) { return Random(count, 0, 0, letters, numbers) } /* Random creates a random string based on a variety of options, using default source of randomness. This method has exactly the same semantics as RandomSeed(int, int, int, bool, bool, []char, *rand.Rand), but instead of using an externally supplied source of randomness, it uses the internal *rand.Rand instance. Parameters: count - the length of random string to create start - the position in set of chars (ASCII/Unicode int) to start at end - the position in set of chars (ASCII/Unicode int) to end before letters - if true, generated string may include alphabetic characters numbers - if true, generated string may include numeric characters chars - the set of chars to choose randoms from. If nil, then it will use the set of all chars. Returns: string - the random string error - an error stemming from an invalid parameter within underlying function, RandomSeed(...) */ func Random(count int, start int, end int, letters bool, numbers bool, chars ...rune) (string, error) { return RandomSeed(count, start, end, letters, numbers, chars, RANDOM) } /* RandomSeed creates a random string based on a variety of options, using supplied source of randomness. If the parameters start and end are both 0, start and end are set to ' ' and 'z', the ASCII printable characters, will be used, unless letters and numbers are both false, in which case, start and end are set to 0 and math.MaxInt32, respectively. If chars is not nil, characters stored in chars that are between start and end are chosen. This method accepts a user-supplied *rand.Rand instance to use as a source of randomness. By seeding a single *rand.Rand instance with a fixed seed and using it for each call, the same random sequence of strings can be generated repeatedly and predictably. Parameters: count - the length of random string to create start - the position in set of chars (ASCII/Unicode decimals) to start at end - the position in set of chars (ASCII/Unicode decimals) to end before letters - if true, generated string may include alphabetic characters numbers - if true, generated string may include numeric characters chars - the set of chars to choose randoms from. If nil, then it will use the set of all chars. random - a source of randomness. Returns: string - the random string error - an error stemming from invalid parameters: if count < 0; or the provided chars array is empty; or end <= start; or end > len(chars) */ func RandomSeed(count int, start int, end int, letters bool, numbers bool, chars []rune, random *rand.Rand) (string, error) { if count == 0 { return "", nil } else if count < 0 { err := fmt.Errorf("randomstringutils illegal argument: Requested random string length %v is less than 0.", count) // equiv to err := errors.New("...") return "", err } if chars != nil && len(chars) == 0 { err := fmt.Errorf("randomstringutils illegal argument: The chars array must not be empty") return "", err } if start == 0 && end == 0 { if chars != nil { end = len(chars) } else { if !letters && !numbers { end = math.MaxInt32 } else { end = 'z' + 1 start = ' ' } } } else { if end <= start { err := fmt.Errorf("randomstringutils illegal argument: Parameter end (%v) must be greater than start (%v)", end, start) return "", err } if chars != nil && end > len(chars) { err := fmt.Errorf("randomstringutils illegal argument: Parameter end (%v) cannot be greater than len(chars) (%v)", end, len(chars)) return "", err } } buffer := make([]rune, count) gap := end - start // high-surrogates range, (\uD800-\uDBFF) = 55296 - 56319 // low-surrogates range, (\uDC00-\uDFFF) = 56320 - 57343 for count != 0 { count-- var ch rune if chars == nil { ch = rune(random.Intn(gap) + start) } else { ch = chars[random.Intn(gap)+start] } if letters && unicode.IsLetter(ch) || numbers && unicode.IsDigit(ch) || !letters && !numbers { if ch >= 56320 && ch <= 57343 { // low surrogate range if count == 0 { count++ } else { // Insert low surrogate buffer[count] = ch count-- // Insert high surrogate buffer[count] = rune(55296 + random.Intn(128)) } } else if ch >= 55296 && ch <= 56191 { // High surrogates range (Partial) if count == 0 { count++ } else { // Insert low surrogate buffer[count] = rune(56320 + random.Intn(128)) count-- // Insert high surrogate buffer[count] = ch } } else if ch >= 56192 && ch <= 56319 { // private high surrogate, skip it count++ } else { // not one of the surrogates* buffer[count] = ch } } else { count++ } } return string(buffer), nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/Masterminds/goutils/cryptorandomstringutils.go
vendor/github.com/Masterminds/goutils/cryptorandomstringutils.go
/* Copyright 2014 Alexander Okoli Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package goutils import ( "crypto/rand" "fmt" "math" "math/big" "unicode" ) /* CryptoRandomNonAlphaNumeric creates a random string whose length is the number of characters specified. Characters will be chosen from the set of all characters (ASCII/Unicode values between 0 to 2,147,483,647 (math.MaxInt32)). Parameter: count - the length of random string to create Returns: string - the random string error - an error stemming from an invalid parameter within underlying function, CryptoRandom(...) */ func CryptoRandomNonAlphaNumeric(count int) (string, error) { return CryptoRandomAlphaNumericCustom(count, false, false) } /* CryptoRandomAscii creates a random string whose length is the number of characters specified. Characters will be chosen from the set of characters whose ASCII value is between 32 and 126 (inclusive). Parameter: count - the length of random string to create Returns: string - the random string error - an error stemming from an invalid parameter within underlying function, CryptoRandom(...) */ func CryptoRandomAscii(count int) (string, error) { return CryptoRandom(count, 32, 127, false, false) } /* CryptoRandomNumeric creates a random string whose length is the number of characters specified. Characters will be chosen from the set of numeric characters. Parameter: count - the length of random string to create Returns: string - the random string error - an error stemming from an invalid parameter within underlying function, CryptoRandom(...) */ func CryptoRandomNumeric(count int) (string, error) { return CryptoRandom(count, 0, 0, false, true) } /* CryptoRandomAlphabetic creates a random string whose length is the number of characters specified. Characters will be chosen from the set of alpha-numeric characters as indicated by the arguments. Parameters: count - the length of random string to create letters - if true, generated string may include alphabetic characters numbers - if true, generated string may include numeric characters Returns: string - the random string error - an error stemming from an invalid parameter within underlying function, CryptoRandom(...) */ func CryptoRandomAlphabetic(count int) (string, error) { return CryptoRandom(count, 0, 0, true, false) } /* CryptoRandomAlphaNumeric creates a random string whose length is the number of characters specified. Characters will be chosen from the set of alpha-numeric characters. Parameter: count - the length of random string to create Returns: string - the random string error - an error stemming from an invalid parameter within underlying function, CryptoRandom(...) */ func CryptoRandomAlphaNumeric(count int) (string, error) { return CryptoRandom(count, 0, 0, true, true) } /* CryptoRandomAlphaNumericCustom creates a random string whose length is the number of characters specified. Characters will be chosen from the set of alpha-numeric characters as indicated by the arguments. Parameters: count - the length of random string to create letters - if true, generated string may include alphabetic characters numbers - if true, generated string may include numeric characters Returns: string - the random string error - an error stemming from an invalid parameter within underlying function, CryptoRandom(...) */ func CryptoRandomAlphaNumericCustom(count int, letters bool, numbers bool) (string, error) { return CryptoRandom(count, 0, 0, letters, numbers) } /* CryptoRandom creates a random string based on a variety of options, using using golang's crypto/rand source of randomness. If the parameters start and end are both 0, start and end are set to ' ' and 'z', the ASCII printable characters, will be used, unless letters and numbers are both false, in which case, start and end are set to 0 and math.MaxInt32, respectively. If chars is not nil, characters stored in chars that are between start and end are chosen. Parameters: count - the length of random string to create start - the position in set of chars (ASCII/Unicode int) to start at end - the position in set of chars (ASCII/Unicode int) to end before letters - if true, generated string may include alphabetic characters numbers - if true, generated string may include numeric characters chars - the set of chars to choose randoms from. If nil, then it will use the set of all chars. Returns: string - the random string error - an error stemming from invalid parameters: if count < 0; or the provided chars array is empty; or end <= start; or end > len(chars) */ func CryptoRandom(count int, start int, end int, letters bool, numbers bool, chars ...rune) (string, error) { if count == 0 { return "", nil } else if count < 0 { err := fmt.Errorf("randomstringutils illegal argument: Requested random string length %v is less than 0.", count) // equiv to err := errors.New("...") return "", err } if chars != nil && len(chars) == 0 { err := fmt.Errorf("randomstringutils illegal argument: The chars array must not be empty") return "", err } if start == 0 && end == 0 { if chars != nil { end = len(chars) } else { if !letters && !numbers { end = math.MaxInt32 } else { end = 'z' + 1 start = ' ' } } } else { if end <= start { err := fmt.Errorf("randomstringutils illegal argument: Parameter end (%v) must be greater than start (%v)", end, start) return "", err } if chars != nil && end > len(chars) { err := fmt.Errorf("randomstringutils illegal argument: Parameter end (%v) cannot be greater than len(chars) (%v)", end, len(chars)) return "", err } } buffer := make([]rune, count) gap := end - start // high-surrogates range, (\uD800-\uDBFF) = 55296 - 56319 // low-surrogates range, (\uDC00-\uDFFF) = 56320 - 57343 for count != 0 { count-- var ch rune if chars == nil { ch = rune(getCryptoRandomInt(gap) + int64(start)) } else { ch = chars[getCryptoRandomInt(gap)+int64(start)] } if letters && unicode.IsLetter(ch) || numbers && unicode.IsDigit(ch) || !letters && !numbers { if ch >= 56320 && ch <= 57343 { // low surrogate range if count == 0 { count++ } else { // Insert low surrogate buffer[count] = ch count-- // Insert high surrogate buffer[count] = rune(55296 + getCryptoRandomInt(128)) } } else if ch >= 55296 && ch <= 56191 { // High surrogates range (Partial) if count == 0 { count++ } else { // Insert low surrogate buffer[count] = rune(56320 + getCryptoRandomInt(128)) count-- // Insert high surrogate buffer[count] = ch } } else if ch >= 56192 && ch <= 56319 { // private high surrogate, skip it count++ } else { // not one of the surrogates* buffer[count] = ch } } else { count++ } } return string(buffer), nil } func getCryptoRandomInt(count int) int64 { nBig, err := rand.Int(rand.Reader, big.NewInt(int64(count))) if err != nil { panic(err) } return nBig.Int64() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/Masterminds/goutils/stringutils.go
vendor/github.com/Masterminds/goutils/stringutils.go
/* Copyright 2014 Alexander Okoli Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package goutils import ( "bytes" "fmt" "strings" "unicode" ) // Typically returned by functions where a searched item cannot be found const INDEX_NOT_FOUND = -1 /* Abbreviate abbreviates a string using ellipses. This will turn the string "Now is the time for all good men" into "Now is the time for..." Specifically, the algorithm is as follows: - If str is less than maxWidth characters long, return it. - Else abbreviate it to (str[0:maxWidth - 3] + "..."). - If maxWidth is less than 4, return an illegal argument error. - In no case will it return a string of length greater than maxWidth. Parameters: str - the string to check maxWidth - maximum length of result string, must be at least 4 Returns: string - abbreviated string error - if the width is too small */ func Abbreviate(str string, maxWidth int) (string, error) { return AbbreviateFull(str, 0, maxWidth) } /* AbbreviateFull abbreviates a string using ellipses. This will turn the string "Now is the time for all good men" into "...is the time for..." This function works like Abbreviate(string, int), but allows you to specify a "left edge" offset. Note that this left edge is not necessarily going to be the leftmost character in the result, or the first character following the ellipses, but it will appear somewhere in the result. In no case will it return a string of length greater than maxWidth. Parameters: str - the string to check offset - left edge of source string maxWidth - maximum length of result string, must be at least 4 Returns: string - abbreviated string error - if the width is too small */ func AbbreviateFull(str string, offset int, maxWidth int) (string, error) { if str == "" { return "", nil } if maxWidth < 4 { err := fmt.Errorf("stringutils illegal argument: Minimum abbreviation width is 4") return "", err } if len(str) <= maxWidth { return str, nil } if offset > len(str) { offset = len(str) } if len(str)-offset < (maxWidth - 3) { // 15 - 5 < 10 - 3 = 10 < 7 offset = len(str) - (maxWidth - 3) } abrevMarker := "..." if offset <= 4 { return str[0:maxWidth-3] + abrevMarker, nil // str.substring(0, maxWidth - 3) + abrevMarker; } if maxWidth < 7 { err := fmt.Errorf("stringutils illegal argument: Minimum abbreviation width with offset is 7") return "", err } if (offset + maxWidth - 3) < len(str) { // 5 + (10-3) < 15 = 12 < 15 abrevStr, _ := Abbreviate(str[offset:len(str)], (maxWidth - 3)) return abrevMarker + abrevStr, nil // abrevMarker + abbreviate(str.substring(offset), maxWidth - 3); } return abrevMarker + str[(len(str)-(maxWidth-3)):len(str)], nil // abrevMarker + str.substring(str.length() - (maxWidth - 3)); } /* DeleteWhiteSpace deletes all whitespaces from a string as defined by unicode.IsSpace(rune). It returns the string without whitespaces. Parameter: str - the string to delete whitespace from, may be nil Returns: the string without whitespaces */ func DeleteWhiteSpace(str string) string { if str == "" { return str } sz := len(str) var chs bytes.Buffer count := 0 for i := 0; i < sz; i++ { ch := rune(str[i]) if !unicode.IsSpace(ch) { chs.WriteRune(ch) count++ } } if count == sz { return str } return chs.String() } /* IndexOfDifference compares two strings, and returns the index at which the strings begin to differ. Parameters: str1 - the first string str2 - the second string Returns: the index where str1 and str2 begin to differ; -1 if they are equal */ func IndexOfDifference(str1 string, str2 string) int { if str1 == str2 { return INDEX_NOT_FOUND } if IsEmpty(str1) || IsEmpty(str2) { return 0 } var i int for i = 0; i < len(str1) && i < len(str2); i++ { if rune(str1[i]) != rune(str2[i]) { break } } if i < len(str2) || i < len(str1) { return i } return INDEX_NOT_FOUND } /* IsBlank checks if a string is whitespace or empty (""). Observe the following behavior: goutils.IsBlank("") = true goutils.IsBlank(" ") = true goutils.IsBlank("bob") = false goutils.IsBlank(" bob ") = false Parameter: str - the string to check Returns: true - if the string is whitespace or empty ("") */ func IsBlank(str string) bool { strLen := len(str) if str == "" || strLen == 0 { return true } for i := 0; i < strLen; i++ { if unicode.IsSpace(rune(str[i])) == false { return false } } return true } /* IndexOf returns the index of the first instance of sub in str, with the search beginning from the index start point specified. -1 is returned if sub is not present in str. An empty string ("") will return -1 (INDEX_NOT_FOUND). A negative start position is treated as zero. A start position greater than the string length returns -1. Parameters: str - the string to check sub - the substring to find start - the start position; negative treated as zero Returns: the first index where the sub string was found (always >= start) */ func IndexOf(str string, sub string, start int) int { if start < 0 { start = 0 } if len(str) < start { return INDEX_NOT_FOUND } if IsEmpty(str) || IsEmpty(sub) { return INDEX_NOT_FOUND } partialIndex := strings.Index(str[start:len(str)], sub) if partialIndex == -1 { return INDEX_NOT_FOUND } return partialIndex + start } // IsEmpty checks if a string is empty (""). Returns true if empty, and false otherwise. func IsEmpty(str string) bool { return len(str) == 0 } // Returns either the passed in string, or if the string is empty, the value of defaultStr. func DefaultString(str string, defaultStr string) string { if IsEmpty(str) { return defaultStr } return str } // Returns either the passed in string, or if the string is whitespace, empty (""), the value of defaultStr. func DefaultIfBlank(str string, defaultStr string) string { if IsBlank(str) { return defaultStr } return str }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/Masterminds/goutils/wordutils.go
vendor/github.com/Masterminds/goutils/wordutils.go
/* Copyright 2014 Alexander Okoli Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Package goutils provides utility functions to manipulate strings in various ways. The code snippets below show examples of how to use goutils. Some functions return errors while others do not, so usage would vary as a result. Example: package main import ( "fmt" "github.com/aokoli/goutils" ) func main() { // EXAMPLE 1: A goutils function which returns no errors fmt.Println (goutils.Initials("John Doe Foo")) // Prints out "JDF" // EXAMPLE 2: A goutils function which returns an error rand1, err1 := goutils.Random (-1, 0, 0, true, true) if err1 != nil { fmt.Println(err1) // Prints out error message because -1 was entered as the first parameter in goutils.Random(...) } else { fmt.Println(rand1) } } */ package goutils import ( "bytes" "strings" "unicode" ) // VERSION indicates the current version of goutils const VERSION = "1.0.0" /* Wrap wraps a single line of text, identifying words by ' '. New lines will be separated by '\n'. Very long words, such as URLs will not be wrapped. Leading spaces on a new line are stripped. Trailing spaces are not stripped. Parameters: str - the string to be word wrapped wrapLength - the column (a column can fit only one character) to wrap the words at, less than 1 is treated as 1 Returns: a line with newlines inserted */ func Wrap(str string, wrapLength int) string { return WrapCustom(str, wrapLength, "", false) } /* WrapCustom wraps a single line of text, identifying words by ' '. Leading spaces on a new line are stripped. Trailing spaces are not stripped. Parameters: str - the string to be word wrapped wrapLength - the column number (a column can fit only one character) to wrap the words at, less than 1 is treated as 1 newLineStr - the string to insert for a new line, "" uses '\n' wrapLongWords - true if long words (such as URLs) should be wrapped Returns: a line with newlines inserted */ func WrapCustom(str string, wrapLength int, newLineStr string, wrapLongWords bool) string { if str == "" { return "" } if newLineStr == "" { newLineStr = "\n" // TODO Assumes "\n" is seperator. Explore SystemUtils.LINE_SEPARATOR from Apache Commons } if wrapLength < 1 { wrapLength = 1 } inputLineLength := len(str) offset := 0 var wrappedLine bytes.Buffer for inputLineLength-offset > wrapLength { if rune(str[offset]) == ' ' { offset++ continue } end := wrapLength + offset + 1 spaceToWrapAt := strings.LastIndex(str[offset:end], " ") + offset if spaceToWrapAt >= offset { // normal word (not longer than wrapLength) wrappedLine.WriteString(str[offset:spaceToWrapAt]) wrappedLine.WriteString(newLineStr) offset = spaceToWrapAt + 1 } else { // long word or URL if wrapLongWords { end := wrapLength + offset // long words are wrapped one line at a time wrappedLine.WriteString(str[offset:end]) wrappedLine.WriteString(newLineStr) offset += wrapLength } else { // long words aren't wrapped, just extended beyond limit end := wrapLength + offset index := strings.IndexRune(str[end:len(str)], ' ') if index == -1 { wrappedLine.WriteString(str[offset:len(str)]) offset = inputLineLength } else { spaceToWrapAt = index + end wrappedLine.WriteString(str[offset:spaceToWrapAt]) wrappedLine.WriteString(newLineStr) offset = spaceToWrapAt + 1 } } } } wrappedLine.WriteString(str[offset:len(str)]) return wrappedLine.String() } /* Capitalize capitalizes all the delimiter separated words in a string. Only the first letter of each word is changed. To convert the rest of each word to lowercase at the same time, use CapitalizeFully(str string, delimiters ...rune). The delimiters represent a set of characters understood to separate words. The first string character and the first non-delimiter character after a delimiter will be capitalized. A "" input string returns "". Capitalization uses the Unicode title case, normally equivalent to upper case. Parameters: str - the string to capitalize delimiters - set of characters to determine capitalization, exclusion of this parameter means whitespace would be delimeter Returns: capitalized string */ func Capitalize(str string, delimiters ...rune) string { var delimLen int if delimiters == nil { delimLen = -1 } else { delimLen = len(delimiters) } if str == "" || delimLen == 0 { return str } buffer := []rune(str) capitalizeNext := true for i := 0; i < len(buffer); i++ { ch := buffer[i] if isDelimiter(ch, delimiters...) { capitalizeNext = true } else if capitalizeNext { buffer[i] = unicode.ToTitle(ch) capitalizeNext = false } } return string(buffer) } /* CapitalizeFully converts all the delimiter separated words in a string into capitalized words, that is each word is made up of a titlecase character and then a series of lowercase characters. The delimiters represent a set of characters understood to separate words. The first string character and the first non-delimiter character after a delimiter will be capitalized. Capitalization uses the Unicode title case, normally equivalent to upper case. Parameters: str - the string to capitalize fully delimiters - set of characters to determine capitalization, exclusion of this parameter means whitespace would be delimeter Returns: capitalized string */ func CapitalizeFully(str string, delimiters ...rune) string { var delimLen int if delimiters == nil { delimLen = -1 } else { delimLen = len(delimiters) } if str == "" || delimLen == 0 { return str } str = strings.ToLower(str) return Capitalize(str, delimiters...) } /* Uncapitalize uncapitalizes all the whitespace separated words in a string. Only the first letter of each word is changed. The delimiters represent a set of characters understood to separate words. The first string character and the first non-delimiter character after a delimiter will be uncapitalized. Whitespace is defined by unicode.IsSpace(char). Parameters: str - the string to uncapitalize fully delimiters - set of characters to determine capitalization, exclusion of this parameter means whitespace would be delimeter Returns: uncapitalized string */ func Uncapitalize(str string, delimiters ...rune) string { var delimLen int if delimiters == nil { delimLen = -1 } else { delimLen = len(delimiters) } if str == "" || delimLen == 0 { return str } buffer := []rune(str) uncapitalizeNext := true // TODO Always makes capitalize/un apply to first char. for i := 0; i < len(buffer); i++ { ch := buffer[i] if isDelimiter(ch, delimiters...) { uncapitalizeNext = true } else if uncapitalizeNext { buffer[i] = unicode.ToLower(ch) uncapitalizeNext = false } } return string(buffer) } /* SwapCase swaps the case of a string using a word based algorithm. Conversion algorithm: Upper case character converts to Lower case Title case character converts to Lower case Lower case character after Whitespace or at start converts to Title case Other Lower case character converts to Upper case Whitespace is defined by unicode.IsSpace(char). Parameters: str - the string to swap case Returns: the changed string */ func SwapCase(str string) string { if str == "" { return str } buffer := []rune(str) whitespace := true for i := 0; i < len(buffer); i++ { ch := buffer[i] if unicode.IsUpper(ch) { buffer[i] = unicode.ToLower(ch) whitespace = false } else if unicode.IsTitle(ch) { buffer[i] = unicode.ToLower(ch) whitespace = false } else if unicode.IsLower(ch) { if whitespace { buffer[i] = unicode.ToTitle(ch) whitespace = false } else { buffer[i] = unicode.ToUpper(ch) } } else { whitespace = unicode.IsSpace(ch) } } return string(buffer) } /* Initials extracts the initial letters from each word in the string. The first letter of the string and all first letters after the defined delimiters are returned as a new string. Their case is not changed. If the delimiters parameter is excluded, then Whitespace is used. Whitespace is defined by unicode.IsSpacea(char). An empty delimiter array returns an empty string. Parameters: str - the string to get initials from delimiters - set of characters to determine words, exclusion of this parameter means whitespace would be delimeter Returns: string of initial letters */ func Initials(str string, delimiters ...rune) string { if str == "" { return str } if delimiters != nil && len(delimiters) == 0 { return "" } strLen := len(str) var buf bytes.Buffer lastWasGap := true for i := 0; i < strLen; i++ { ch := rune(str[i]) if isDelimiter(ch, delimiters...) { lastWasGap = true } else if lastWasGap { buf.WriteRune(ch) lastWasGap = false } } return buf.String() } // private function (lower case func name) func isDelimiter(ch rune, delimiters ...rune) bool { if delimiters == nil { return unicode.IsSpace(ch) } for _, delimiter := range delimiters { if ch == delimiter { return true } } return false }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/Masterminds/sprig/v3/network.go
vendor/github.com/Masterminds/sprig/v3/network.go
package sprig import ( "math/rand" "net" ) func getHostByName(name string) string { addrs, _ := net.LookupHost(name) //TODO: add error handing when release v3 comes out return addrs[rand.Intn(len(addrs))] }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/Masterminds/sprig/v3/defaults.go
vendor/github.com/Masterminds/sprig/v3/defaults.go
package sprig import ( "bytes" "encoding/json" "math/rand" "reflect" "strings" "time" ) func init() { rand.Seed(time.Now().UnixNano()) } // dfault checks whether `given` is set, and returns default if not set. // // This returns `d` if `given` appears not to be set, and `given` otherwise. // // For numeric types 0 is unset. // For strings, maps, arrays, and slices, len() = 0 is considered unset. // For bool, false is unset. // Structs are never considered unset. // // For everything else, including pointers, a nil value is unset. func dfault(d interface{}, given ...interface{}) interface{} { if empty(given) || empty(given[0]) { return d } return given[0] } // empty returns true if the given value has the zero value for its type. func empty(given interface{}) bool { g := reflect.ValueOf(given) if !g.IsValid() { return true } // Basically adapted from text/template.isTrue switch g.Kind() { default: return g.IsNil() case reflect.Array, reflect.Slice, reflect.Map, reflect.String: return g.Len() == 0 case reflect.Bool: return !g.Bool() case reflect.Complex64, reflect.Complex128: return g.Complex() == 0 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return g.Int() == 0 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return g.Uint() == 0 case reflect.Float32, reflect.Float64: return g.Float() == 0 case reflect.Struct: return false } } // coalesce returns the first non-empty value. func coalesce(v ...interface{}) interface{} { for _, val := range v { if !empty(val) { return val } } return nil } // all returns true if empty(x) is false for all values x in the list. // If the list is empty, return true. func all(v ...interface{}) bool { for _, val := range v { if empty(val) { return false } } return true } // any returns true if empty(x) is false for any x in the list. // If the list is empty, return false. func any(v ...interface{}) bool { for _, val := range v { if !empty(val) { return true } } return false } // fromJson decodes JSON into a structured value, ignoring errors. func fromJson(v string) interface{} { output, _ := mustFromJson(v) return output } // mustFromJson decodes JSON into a structured value, returning errors. func mustFromJson(v string) (interface{}, error) { var output interface{} err := json.Unmarshal([]byte(v), &output) return output, err } // toJson encodes an item into a JSON string func toJson(v interface{}) string { output, _ := json.Marshal(v) return string(output) } func mustToJson(v interface{}) (string, error) { output, err := json.Marshal(v) if err != nil { return "", err } return string(output), nil } // toPrettyJson encodes an item into a pretty (indented) JSON string func toPrettyJson(v interface{}) string { output, _ := json.MarshalIndent(v, "", " ") return string(output) } func mustToPrettyJson(v interface{}) (string, error) { output, err := json.MarshalIndent(v, "", " ") if err != nil { return "", err } return string(output), nil } // toRawJson encodes an item into a JSON string with no escaping of HTML characters. func toRawJson(v interface{}) string { output, err := mustToRawJson(v) if err != nil { panic(err) } return string(output) } // mustToRawJson encodes an item into a JSON string with no escaping of HTML characters. func mustToRawJson(v interface{}) (string, error) { buf := new(bytes.Buffer) enc := json.NewEncoder(buf) enc.SetEscapeHTML(false) err := enc.Encode(&v) if err != nil { return "", err } return strings.TrimSuffix(buf.String(), "\n"), nil } // ternary returns the first value if the last value is true, otherwise returns the second value. func ternary(vt interface{}, vf interface{}, v bool) interface{} { if v { return vt } return vf }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/Masterminds/sprig/v3/url.go
vendor/github.com/Masterminds/sprig/v3/url.go
package sprig import ( "fmt" "net/url" "reflect" ) func dictGetOrEmpty(dict map[string]interface{}, key string) string { value, ok := dict[key] if !ok { return "" } tp := reflect.TypeOf(value).Kind() if tp != reflect.String { panic(fmt.Sprintf("unable to parse %s key, must be of type string, but %s found", key, tp.String())) } return reflect.ValueOf(value).String() } // parses given URL to return dict object func urlParse(v string) map[string]interface{} { dict := map[string]interface{}{} parsedURL, err := url.Parse(v) if err != nil { panic(fmt.Sprintf("unable to parse url: %s", err)) } dict["scheme"] = parsedURL.Scheme dict["host"] = parsedURL.Host dict["hostname"] = parsedURL.Hostname() dict["path"] = parsedURL.Path dict["query"] = parsedURL.RawQuery dict["opaque"] = parsedURL.Opaque dict["fragment"] = parsedURL.Fragment if parsedURL.User != nil { dict["userinfo"] = parsedURL.User.String() } else { dict["userinfo"] = "" } return dict } // join given dict to URL string func urlJoin(d map[string]interface{}) string { resURL := url.URL{ Scheme: dictGetOrEmpty(d, "scheme"), Host: dictGetOrEmpty(d, "host"), Path: dictGetOrEmpty(d, "path"), RawQuery: dictGetOrEmpty(d, "query"), Opaque: dictGetOrEmpty(d, "opaque"), Fragment: dictGetOrEmpty(d, "fragment"), } userinfo := dictGetOrEmpty(d, "userinfo") var user *url.Userinfo if userinfo != "" { tempURL, err := url.Parse(fmt.Sprintf("proto://%s@host", userinfo)) if err != nil { panic(fmt.Sprintf("unable to parse userinfo in dict: %s", err)) } user = tempURL.User } resURL.User = user return resURL.String() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/Masterminds/sprig/v3/strings.go
vendor/github.com/Masterminds/sprig/v3/strings.go
package sprig import ( "encoding/base32" "encoding/base64" "fmt" "reflect" "strconv" "strings" util "github.com/Masterminds/goutils" ) func base64encode(v string) string { return base64.StdEncoding.EncodeToString([]byte(v)) } func base64decode(v string) string { data, err := base64.StdEncoding.DecodeString(v) if err != nil { return err.Error() } return string(data) } func base32encode(v string) string { return base32.StdEncoding.EncodeToString([]byte(v)) } func base32decode(v string) string { data, err := base32.StdEncoding.DecodeString(v) if err != nil { return err.Error() } return string(data) } func abbrev(width int, s string) string { if width < 4 { return s } r, _ := util.Abbreviate(s, width) return r } func abbrevboth(left, right int, s string) string { if right < 4 || left > 0 && right < 7 { return s } r, _ := util.AbbreviateFull(s, left, right) return r } func initials(s string) string { // Wrap this just to eliminate the var args, which templates don't do well. return util.Initials(s) } func randAlphaNumeric(count int) string { // It is not possible, it appears, to actually generate an error here. r, _ := util.CryptoRandomAlphaNumeric(count) return r } func randAlpha(count int) string { r, _ := util.CryptoRandomAlphabetic(count) return r } func randAscii(count int) string { r, _ := util.CryptoRandomAscii(count) return r } func randNumeric(count int) string { r, _ := util.CryptoRandomNumeric(count) return r } func untitle(str string) string { return util.Uncapitalize(str) } func quote(str ...interface{}) string { out := make([]string, 0, len(str)) for _, s := range str { if s != nil { out = append(out, fmt.Sprintf("%q", strval(s))) } } return strings.Join(out, " ") } func squote(str ...interface{}) string { out := make([]string, 0, len(str)) for _, s := range str { if s != nil { out = append(out, fmt.Sprintf("'%v'", s)) } } return strings.Join(out, " ") } func cat(v ...interface{}) string { v = removeNilElements(v) r := strings.TrimSpace(strings.Repeat("%v ", len(v))) return fmt.Sprintf(r, v...) } func indent(spaces int, v string) string { pad := strings.Repeat(" ", spaces) return pad + strings.Replace(v, "\n", "\n"+pad, -1) } func nindent(spaces int, v string) string { return "\n" + indent(spaces, v) } func replace(old, new, src string) string { return strings.Replace(src, old, new, -1) } func plural(one, many string, count int) string { if count == 1 { return one } return many } func strslice(v interface{}) []string { switch v := v.(type) { case []string: return v case []interface{}: b := make([]string, 0, len(v)) for _, s := range v { if s != nil { b = append(b, strval(s)) } } return b default: val := reflect.ValueOf(v) switch val.Kind() { case reflect.Array, reflect.Slice: l := val.Len() b := make([]string, 0, l) for i := 0; i < l; i++ { value := val.Index(i).Interface() if value != nil { b = append(b, strval(value)) } } return b default: if v == nil { return []string{} } return []string{strval(v)} } } } func removeNilElements(v []interface{}) []interface{} { newSlice := make([]interface{}, 0, len(v)) for _, i := range v { if i != nil { newSlice = append(newSlice, i) } } return newSlice } func strval(v interface{}) string { switch v := v.(type) { case string: return v case []byte: return string(v) case error: return v.Error() case fmt.Stringer: return v.String() default: return fmt.Sprintf("%v", v) } } func trunc(c int, s string) string { if c < 0 && len(s)+c > 0 { return s[len(s)+c:] } if c >= 0 && len(s) > c { return s[:c] } return s } func join(sep string, v interface{}) string { return strings.Join(strslice(v), sep) } func split(sep, orig string) map[string]string { parts := strings.Split(orig, sep) res := make(map[string]string, len(parts)) for i, v := range parts { res["_"+strconv.Itoa(i)] = v } return res } func splitn(sep string, n int, orig string) map[string]string { parts := strings.SplitN(orig, sep, n) res := make(map[string]string, len(parts)) for i, v := range parts { res["_"+strconv.Itoa(i)] = v } return res } // substring creates a substring of the given string. // // If start is < 0, this calls string[:end]. // // If start is >= 0 and end < 0 or end bigger than s length, this calls string[start:] // // Otherwise, this calls string[start, end]. func substring(start, end int, s string) string { if start < 0 { return s[:end] } if end < 0 || end > len(s) { return s[start:] } return s[start:end] }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/Masterminds/sprig/v3/date.go
vendor/github.com/Masterminds/sprig/v3/date.go
package sprig import ( "strconv" "time" ) // Given a format and a date, format the date string. // // Date can be a `time.Time` or an `int, int32, int64`. // In the later case, it is treated as seconds since UNIX // epoch. func date(fmt string, date interface{}) string { return dateInZone(fmt, date, "Local") } func htmlDate(date interface{}) string { return dateInZone("2006-01-02", date, "Local") } func htmlDateInZone(date interface{}, zone string) string { return dateInZone("2006-01-02", date, zone) } func dateInZone(fmt string, date interface{}, zone string) string { var t time.Time switch date := date.(type) { default: t = time.Now() case time.Time: t = date case *time.Time: t = *date case int64: t = time.Unix(date, 0) case int: t = time.Unix(int64(date), 0) case int32: t = time.Unix(int64(date), 0) } loc, err := time.LoadLocation(zone) if err != nil { loc, _ = time.LoadLocation("UTC") } return t.In(loc).Format(fmt) } func dateModify(fmt string, date time.Time) time.Time { d, err := time.ParseDuration(fmt) if err != nil { return date } return date.Add(d) } func mustDateModify(fmt string, date time.Time) (time.Time, error) { d, err := time.ParseDuration(fmt) if err != nil { return time.Time{}, err } return date.Add(d), nil } func dateAgo(date interface{}) string { var t time.Time switch date := date.(type) { default: t = time.Now() case time.Time: t = date case int64: t = time.Unix(date, 0) case int: t = time.Unix(int64(date), 0) } // Drop resolution to seconds duration := time.Since(t).Round(time.Second) return duration.String() } func duration(sec interface{}) string { var n int64 switch value := sec.(type) { default: n = 0 case string: n, _ = strconv.ParseInt(value, 10, 64) case int64: n = value } return (time.Duration(n) * time.Second).String() } func durationRound(duration interface{}) string { var d time.Duration switch duration := duration.(type) { default: d = 0 case string: d, _ = time.ParseDuration(duration) case int64: d = time.Duration(duration) case time.Time: d = time.Since(duration) } u := uint64(d) neg := d < 0 if neg { u = -u } var ( year = uint64(time.Hour) * 24 * 365 month = uint64(time.Hour) * 24 * 30 day = uint64(time.Hour) * 24 hour = uint64(time.Hour) minute = uint64(time.Minute) second = uint64(time.Second) ) switch { case u > year: return strconv.FormatUint(u/year, 10) + "y" case u > month: return strconv.FormatUint(u/month, 10) + "mo" case u > day: return strconv.FormatUint(u/day, 10) + "d" case u > hour: return strconv.FormatUint(u/hour, 10) + "h" case u > minute: return strconv.FormatUint(u/minute, 10) + "m" case u > second: return strconv.FormatUint(u/second, 10) + "s" } return "0s" } func toDate(fmt, str string) time.Time { t, _ := time.ParseInLocation(fmt, str, time.Local) return t } func mustToDate(fmt, str string) (time.Time, error) { return time.ParseInLocation(fmt, str, time.Local) } func unixEpoch(date time.Time) string { return strconv.FormatInt(date.Unix(), 10) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/Masterminds/sprig/v3/list.go
vendor/github.com/Masterminds/sprig/v3/list.go
package sprig import ( "fmt" "math" "reflect" "sort" ) // Reflection is used in these functions so that slices and arrays of strings, // ints, and other types not implementing []interface{} can be worked with. // For example, this is useful if you need to work on the output of regexs. func list(v ...interface{}) []interface{} { return v } func push(list interface{}, v interface{}) []interface{} { l, err := mustPush(list, v) if err != nil { panic(err) } return l } func mustPush(list interface{}, v interface{}) ([]interface{}, error) { tp := reflect.TypeOf(list).Kind() switch tp { case reflect.Slice, reflect.Array: l2 := reflect.ValueOf(list) l := l2.Len() nl := make([]interface{}, l) for i := 0; i < l; i++ { nl[i] = l2.Index(i).Interface() } return append(nl, v), nil default: return nil, fmt.Errorf("Cannot push on type %s", tp) } } func prepend(list interface{}, v interface{}) []interface{} { l, err := mustPrepend(list, v) if err != nil { panic(err) } return l } func mustPrepend(list interface{}, v interface{}) ([]interface{}, error) { //return append([]interface{}{v}, list...) tp := reflect.TypeOf(list).Kind() switch tp { case reflect.Slice, reflect.Array: l2 := reflect.ValueOf(list) l := l2.Len() nl := make([]interface{}, l) for i := 0; i < l; i++ { nl[i] = l2.Index(i).Interface() } return append([]interface{}{v}, nl...), nil default: return nil, fmt.Errorf("Cannot prepend on type %s", tp) } } func chunk(size int, list interface{}) [][]interface{} { l, err := mustChunk(size, list) if err != nil { panic(err) } return l } func mustChunk(size int, list interface{}) ([][]interface{}, error) { tp := reflect.TypeOf(list).Kind() switch tp { case reflect.Slice, reflect.Array: l2 := reflect.ValueOf(list) l := l2.Len() cs := int(math.Floor(float64(l-1)/float64(size)) + 1) nl := make([][]interface{}, cs) for i := 0; i < cs; i++ { clen := size if i == cs-1 { clen = int(math.Floor(math.Mod(float64(l), float64(size)))) if clen == 0 { clen = size } } nl[i] = make([]interface{}, clen) for j := 0; j < clen; j++ { ix := i*size + j nl[i][j] = l2.Index(ix).Interface() } } return nl, nil default: return nil, fmt.Errorf("Cannot chunk type %s", tp) } } func last(list interface{}) interface{} { l, err := mustLast(list) if err != nil { panic(err) } return l } func mustLast(list interface{}) (interface{}, error) { tp := reflect.TypeOf(list).Kind() switch tp { case reflect.Slice, reflect.Array: l2 := reflect.ValueOf(list) l := l2.Len() if l == 0 { return nil, nil } return l2.Index(l - 1).Interface(), nil default: return nil, fmt.Errorf("Cannot find last on type %s", tp) } } func first(list interface{}) interface{} { l, err := mustFirst(list) if err != nil { panic(err) } return l } func mustFirst(list interface{}) (interface{}, error) { tp := reflect.TypeOf(list).Kind() switch tp { case reflect.Slice, reflect.Array: l2 := reflect.ValueOf(list) l := l2.Len() if l == 0 { return nil, nil } return l2.Index(0).Interface(), nil default: return nil, fmt.Errorf("Cannot find first on type %s", tp) } } func rest(list interface{}) []interface{} { l, err := mustRest(list) if err != nil { panic(err) } return l } func mustRest(list interface{}) ([]interface{}, error) { tp := reflect.TypeOf(list).Kind() switch tp { case reflect.Slice, reflect.Array: l2 := reflect.ValueOf(list) l := l2.Len() if l == 0 { return nil, nil } nl := make([]interface{}, l-1) for i := 1; i < l; i++ { nl[i-1] = l2.Index(i).Interface() } return nl, nil default: return nil, fmt.Errorf("Cannot find rest on type %s", tp) } } func initial(list interface{}) []interface{} { l, err := mustInitial(list) if err != nil { panic(err) } return l } func mustInitial(list interface{}) ([]interface{}, error) { tp := reflect.TypeOf(list).Kind() switch tp { case reflect.Slice, reflect.Array: l2 := reflect.ValueOf(list) l := l2.Len() if l == 0 { return nil, nil } nl := make([]interface{}, l-1) for i := 0; i < l-1; i++ { nl[i] = l2.Index(i).Interface() } return nl, nil default: return nil, fmt.Errorf("Cannot find initial on type %s", tp) } } func sortAlpha(list interface{}) []string { k := reflect.Indirect(reflect.ValueOf(list)).Kind() switch k { case reflect.Slice, reflect.Array: a := strslice(list) s := sort.StringSlice(a) s.Sort() return s } return []string{strval(list)} } func reverse(v interface{}) []interface{} { l, err := mustReverse(v) if err != nil { panic(err) } return l } func mustReverse(v interface{}) ([]interface{}, error) { tp := reflect.TypeOf(v).Kind() switch tp { case reflect.Slice, reflect.Array: l2 := reflect.ValueOf(v) l := l2.Len() // We do not sort in place because the incoming array should not be altered. nl := make([]interface{}, l) for i := 0; i < l; i++ { nl[l-i-1] = l2.Index(i).Interface() } return nl, nil default: return nil, fmt.Errorf("Cannot find reverse on type %s", tp) } } func compact(list interface{}) []interface{} { l, err := mustCompact(list) if err != nil { panic(err) } return l } func mustCompact(list interface{}) ([]interface{}, error) { tp := reflect.TypeOf(list).Kind() switch tp { case reflect.Slice, reflect.Array: l2 := reflect.ValueOf(list) l := l2.Len() nl := []interface{}{} var item interface{} for i := 0; i < l; i++ { item = l2.Index(i).Interface() if !empty(item) { nl = append(nl, item) } } return nl, nil default: return nil, fmt.Errorf("Cannot compact on type %s", tp) } } func uniq(list interface{}) []interface{} { l, err := mustUniq(list) if err != nil { panic(err) } return l } func mustUniq(list interface{}) ([]interface{}, error) { tp := reflect.TypeOf(list).Kind() switch tp { case reflect.Slice, reflect.Array: l2 := reflect.ValueOf(list) l := l2.Len() dest := []interface{}{} var item interface{} for i := 0; i < l; i++ { item = l2.Index(i).Interface() if !inList(dest, item) { dest = append(dest, item) } } return dest, nil default: return nil, fmt.Errorf("Cannot find uniq on type %s", tp) } } func inList(haystack []interface{}, needle interface{}) bool { for _, h := range haystack { if reflect.DeepEqual(needle, h) { return true } } return false } func without(list interface{}, omit ...interface{}) []interface{} { l, err := mustWithout(list, omit...) if err != nil { panic(err) } return l } func mustWithout(list interface{}, omit ...interface{}) ([]interface{}, error) { tp := reflect.TypeOf(list).Kind() switch tp { case reflect.Slice, reflect.Array: l2 := reflect.ValueOf(list) l := l2.Len() res := []interface{}{} var item interface{} for i := 0; i < l; i++ { item = l2.Index(i).Interface() if !inList(omit, item) { res = append(res, item) } } return res, nil default: return nil, fmt.Errorf("Cannot find without on type %s", tp) } } func has(needle interface{}, haystack interface{}) bool { l, err := mustHas(needle, haystack) if err != nil { panic(err) } return l } func mustHas(needle interface{}, haystack interface{}) (bool, error) { if haystack == nil { return false, nil } tp := reflect.TypeOf(haystack).Kind() switch tp { case reflect.Slice, reflect.Array: l2 := reflect.ValueOf(haystack) var item interface{} l := l2.Len() for i := 0; i < l; i++ { item = l2.Index(i).Interface() if reflect.DeepEqual(needle, item) { return true, nil } } return false, nil default: return false, fmt.Errorf("Cannot find has on type %s", tp) } } // $list := [1, 2, 3, 4, 5] // slice $list -> list[0:5] = list[:] // slice $list 0 3 -> list[0:3] = list[:3] // slice $list 3 5 -> list[3:5] // slice $list 3 -> list[3:5] = list[3:] func slice(list interface{}, indices ...interface{}) interface{} { l, err := mustSlice(list, indices...) if err != nil { panic(err) } return l } func mustSlice(list interface{}, indices ...interface{}) (interface{}, error) { tp := reflect.TypeOf(list).Kind() switch tp { case reflect.Slice, reflect.Array: l2 := reflect.ValueOf(list) l := l2.Len() if l == 0 { return nil, nil } var start, end int if len(indices) > 0 { start = toInt(indices[0]) } if len(indices) < 2 { end = l } else { end = toInt(indices[1]) } return l2.Slice(start, end).Interface(), nil default: return nil, fmt.Errorf("list should be type of slice or array but %s", tp) } } func concat(lists ...interface{}) interface{} { var res []interface{} for _, list := range lists { tp := reflect.TypeOf(list).Kind() switch tp { case reflect.Slice, reflect.Array: l2 := reflect.ValueOf(list) for i := 0; i < l2.Len(); i++ { res = append(res, l2.Index(i).Interface()) } default: panic(fmt.Sprintf("Cannot concat type %s as list", tp)) } } return res }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/Masterminds/sprig/v3/reflect.go
vendor/github.com/Masterminds/sprig/v3/reflect.go
package sprig import ( "fmt" "reflect" ) // typeIs returns true if the src is the type named in target. func typeIs(target string, src interface{}) bool { return target == typeOf(src) } func typeIsLike(target string, src interface{}) bool { t := typeOf(src) return target == t || "*"+target == t } func typeOf(src interface{}) string { return fmt.Sprintf("%T", src) } func kindIs(target string, src interface{}) bool { return target == kindOf(src) } func kindOf(src interface{}) string { return reflect.ValueOf(src).Kind().String() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/Masterminds/sprig/v3/crypto.go
vendor/github.com/Masterminds/sprig/v3/crypto.go
package sprig import ( "bytes" "crypto" "crypto/aes" "crypto/cipher" "crypto/dsa" "crypto/ecdsa" "crypto/ed25519" "crypto/elliptic" "crypto/hmac" "crypto/rand" "crypto/rsa" "crypto/sha1" "crypto/sha256" "crypto/sha512" "crypto/x509" "crypto/x509/pkix" "encoding/asn1" "encoding/base64" "encoding/binary" "encoding/hex" "encoding/pem" "errors" "fmt" "hash/adler32" "io" "math/big" "net" "time" "strings" "github.com/google/uuid" bcrypt_lib "golang.org/x/crypto/bcrypt" "golang.org/x/crypto/scrypt" ) func sha512sum(input string) string { hash := sha512.Sum512([]byte(input)) return hex.EncodeToString(hash[:]) } func sha256sum(input string) string { hash := sha256.Sum256([]byte(input)) return hex.EncodeToString(hash[:]) } func sha1sum(input string) string { hash := sha1.Sum([]byte(input)) return hex.EncodeToString(hash[:]) } func adler32sum(input string) string { hash := adler32.Checksum([]byte(input)) return fmt.Sprintf("%d", hash) } func bcrypt(input string) string { hash, err := bcrypt_lib.GenerateFromPassword([]byte(input), bcrypt_lib.DefaultCost) if err != nil { return fmt.Sprintf("failed to encrypt string with bcrypt: %s", err) } return string(hash) } func htpasswd(username string, password string) string { if strings.Contains(username, ":") { return fmt.Sprintf("invalid username: %s", username) } return fmt.Sprintf("%s:%s", username, bcrypt(password)) } func randBytes(count int) (string, error) { buf := make([]byte, count) if _, err := rand.Read(buf); err != nil { return "", err } return base64.StdEncoding.EncodeToString(buf), nil } // uuidv4 provides a safe and secure UUID v4 implementation func uuidv4() string { return uuid.New().String() } var masterPasswordSeed = "com.lyndir.masterpassword" var passwordTypeTemplates = map[string][][]byte{ "maximum": {[]byte("anoxxxxxxxxxxxxxxxxx"), []byte("axxxxxxxxxxxxxxxxxno")}, "long": {[]byte("CvcvnoCvcvCvcv"), []byte("CvcvCvcvnoCvcv"), []byte("CvcvCvcvCvcvno"), []byte("CvccnoCvcvCvcv"), []byte("CvccCvcvnoCvcv"), []byte("CvccCvcvCvcvno"), []byte("CvcvnoCvccCvcv"), []byte("CvcvCvccnoCvcv"), []byte("CvcvCvccCvcvno"), []byte("CvcvnoCvcvCvcc"), []byte("CvcvCvcvnoCvcc"), []byte("CvcvCvcvCvccno"), []byte("CvccnoCvccCvcv"), []byte("CvccCvccnoCvcv"), []byte("CvccCvccCvcvno"), []byte("CvcvnoCvccCvcc"), []byte("CvcvCvccnoCvcc"), []byte("CvcvCvccCvccno"), []byte("CvccnoCvcvCvcc"), []byte("CvccCvcvnoCvcc"), []byte("CvccCvcvCvccno")}, "medium": {[]byte("CvcnoCvc"), []byte("CvcCvcno")}, "short": {[]byte("Cvcn")}, "basic": {[]byte("aaanaaan"), []byte("aannaaan"), []byte("aaannaaa")}, "pin": {[]byte("nnnn")}, } var templateCharacters = map[byte]string{ 'V': "AEIOU", 'C': "BCDFGHJKLMNPQRSTVWXYZ", 'v': "aeiou", 'c': "bcdfghjklmnpqrstvwxyz", 'A': "AEIOUBCDFGHJKLMNPQRSTVWXYZ", 'a': "AEIOUaeiouBCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz", 'n': "0123456789", 'o': "@&%?,=[]_:-+*$#!'^~;()/.", 'x': "AEIOUaeiouBCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz0123456789!@#$%^&*()", } func derivePassword(counter uint32, passwordType, password, user, site string) string { var templates = passwordTypeTemplates[passwordType] if templates == nil { return fmt.Sprintf("cannot find password template %s", passwordType) } var buffer bytes.Buffer buffer.WriteString(masterPasswordSeed) binary.Write(&buffer, binary.BigEndian, uint32(len(user))) buffer.WriteString(user) salt := buffer.Bytes() key, err := scrypt.Key([]byte(password), salt, 32768, 8, 2, 64) if err != nil { return fmt.Sprintf("failed to derive password: %s", err) } buffer.Truncate(len(masterPasswordSeed)) binary.Write(&buffer, binary.BigEndian, uint32(len(site))) buffer.WriteString(site) binary.Write(&buffer, binary.BigEndian, counter) var hmacv = hmac.New(sha256.New, key) hmacv.Write(buffer.Bytes()) var seed = hmacv.Sum(nil) var temp = templates[int(seed[0])%len(templates)] buffer.Truncate(0) for i, element := range temp { passChars := templateCharacters[element] passChar := passChars[int(seed[i+1])%len(passChars)] buffer.WriteByte(passChar) } return buffer.String() } func generatePrivateKey(typ string) string { var priv interface{} var err error switch typ { case "", "rsa": // good enough for government work priv, err = rsa.GenerateKey(rand.Reader, 4096) case "dsa": key := new(dsa.PrivateKey) // again, good enough for government work if err = dsa.GenerateParameters(&key.Parameters, rand.Reader, dsa.L2048N256); err != nil { return fmt.Sprintf("failed to generate dsa params: %s", err) } err = dsa.GenerateKey(key, rand.Reader) priv = key case "ecdsa": // again, good enough for government work priv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) case "ed25519": _, priv, err = ed25519.GenerateKey(rand.Reader) default: return "Unknown type " + typ } if err != nil { return fmt.Sprintf("failed to generate private key: %s", err) } return string(pem.EncodeToMemory(pemBlockForKey(priv))) } // DSAKeyFormat stores the format for DSA keys. // Used by pemBlockForKey type DSAKeyFormat struct { Version int P, Q, G, Y, X *big.Int } func pemBlockForKey(priv interface{}) *pem.Block { switch k := priv.(type) { case *rsa.PrivateKey: return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)} case *dsa.PrivateKey: val := DSAKeyFormat{ P: k.P, Q: k.Q, G: k.G, Y: k.Y, X: k.X, } bytes, _ := asn1.Marshal(val) return &pem.Block{Type: "DSA PRIVATE KEY", Bytes: bytes} case *ecdsa.PrivateKey: b, _ := x509.MarshalECPrivateKey(k) return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b} default: // attempt PKCS#8 format for all other keys b, err := x509.MarshalPKCS8PrivateKey(k) if err != nil { return nil } return &pem.Block{Type: "PRIVATE KEY", Bytes: b} } } func parsePrivateKeyPEM(pemBlock string) (crypto.PrivateKey, error) { block, _ := pem.Decode([]byte(pemBlock)) if block == nil { return nil, errors.New("no PEM data in input") } if block.Type == "PRIVATE KEY" { priv, err := x509.ParsePKCS8PrivateKey(block.Bytes) if err != nil { return nil, fmt.Errorf("decoding PEM as PKCS#8: %s", err) } return priv, nil } else if !strings.HasSuffix(block.Type, " PRIVATE KEY") { return nil, fmt.Errorf("no private key data in PEM block of type %s", block.Type) } switch block.Type[:len(block.Type)-12] { // strip " PRIVATE KEY" case "RSA": priv, err := x509.ParsePKCS1PrivateKey(block.Bytes) if err != nil { return nil, fmt.Errorf("parsing RSA private key from PEM: %s", err) } return priv, nil case "EC": priv, err := x509.ParseECPrivateKey(block.Bytes) if err != nil { return nil, fmt.Errorf("parsing EC private key from PEM: %s", err) } return priv, nil case "DSA": var k DSAKeyFormat _, err := asn1.Unmarshal(block.Bytes, &k) if err != nil { return nil, fmt.Errorf("parsing DSA private key from PEM: %s", err) } priv := &dsa.PrivateKey{ PublicKey: dsa.PublicKey{ Parameters: dsa.Parameters{ P: k.P, Q: k.Q, G: k.G, }, Y: k.Y, }, X: k.X, } return priv, nil default: return nil, fmt.Errorf("invalid private key type %s", block.Type) } } func getPublicKey(priv crypto.PrivateKey) (crypto.PublicKey, error) { switch k := priv.(type) { case interface{ Public() crypto.PublicKey }: return k.Public(), nil case *dsa.PrivateKey: return &k.PublicKey, nil default: return nil, fmt.Errorf("unable to get public key for type %T", priv) } } type certificate struct { Cert string Key string } func buildCustomCertificate(b64cert string, b64key string) (certificate, error) { crt := certificate{} cert, err := base64.StdEncoding.DecodeString(b64cert) if err != nil { return crt, errors.New("unable to decode base64 certificate") } key, err := base64.StdEncoding.DecodeString(b64key) if err != nil { return crt, errors.New("unable to decode base64 private key") } decodedCert, _ := pem.Decode(cert) if decodedCert == nil { return crt, errors.New("unable to decode certificate") } _, err = x509.ParseCertificate(decodedCert.Bytes) if err != nil { return crt, fmt.Errorf( "error parsing certificate: decodedCert.Bytes: %s", err, ) } _, err = parsePrivateKeyPEM(string(key)) if err != nil { return crt, fmt.Errorf( "error parsing private key: %s", err, ) } crt.Cert = string(cert) crt.Key = string(key) return crt, nil } func generateCertificateAuthority( cn string, daysValid int, ) (certificate, error) { priv, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { return certificate{}, fmt.Errorf("error generating rsa key: %s", err) } return generateCertificateAuthorityWithKeyInternal(cn, daysValid, priv) } func generateCertificateAuthorityWithPEMKey( cn string, daysValid int, privPEM string, ) (certificate, error) { priv, err := parsePrivateKeyPEM(privPEM) if err != nil { return certificate{}, fmt.Errorf("parsing private key: %s", err) } return generateCertificateAuthorityWithKeyInternal(cn, daysValid, priv) } func generateCertificateAuthorityWithKeyInternal( cn string, daysValid int, priv crypto.PrivateKey, ) (certificate, error) { ca := certificate{} template, err := getBaseCertTemplate(cn, nil, nil, daysValid) if err != nil { return ca, err } // Override KeyUsage and IsCA template.KeyUsage = x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign template.IsCA = true ca.Cert, ca.Key, err = getCertAndKey(template, priv, template, priv) return ca, err } func generateSelfSignedCertificate( cn string, ips []interface{}, alternateDNS []interface{}, daysValid int, ) (certificate, error) { priv, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { return certificate{}, fmt.Errorf("error generating rsa key: %s", err) } return generateSelfSignedCertificateWithKeyInternal(cn, ips, alternateDNS, daysValid, priv) } func generateSelfSignedCertificateWithPEMKey( cn string, ips []interface{}, alternateDNS []interface{}, daysValid int, privPEM string, ) (certificate, error) { priv, err := parsePrivateKeyPEM(privPEM) if err != nil { return certificate{}, fmt.Errorf("parsing private key: %s", err) } return generateSelfSignedCertificateWithKeyInternal(cn, ips, alternateDNS, daysValid, priv) } func generateSelfSignedCertificateWithKeyInternal( cn string, ips []interface{}, alternateDNS []interface{}, daysValid int, priv crypto.PrivateKey, ) (certificate, error) { cert := certificate{} template, err := getBaseCertTemplate(cn, ips, alternateDNS, daysValid) if err != nil { return cert, err } cert.Cert, cert.Key, err = getCertAndKey(template, priv, template, priv) return cert, err } func generateSignedCertificate( cn string, ips []interface{}, alternateDNS []interface{}, daysValid int, ca certificate, ) (certificate, error) { priv, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { return certificate{}, fmt.Errorf("error generating rsa key: %s", err) } return generateSignedCertificateWithKeyInternal(cn, ips, alternateDNS, daysValid, ca, priv) } func generateSignedCertificateWithPEMKey( cn string, ips []interface{}, alternateDNS []interface{}, daysValid int, ca certificate, privPEM string, ) (certificate, error) { priv, err := parsePrivateKeyPEM(privPEM) if err != nil { return certificate{}, fmt.Errorf("parsing private key: %s", err) } return generateSignedCertificateWithKeyInternal(cn, ips, alternateDNS, daysValid, ca, priv) } func generateSignedCertificateWithKeyInternal( cn string, ips []interface{}, alternateDNS []interface{}, daysValid int, ca certificate, priv crypto.PrivateKey, ) (certificate, error) { cert := certificate{} decodedSignerCert, _ := pem.Decode([]byte(ca.Cert)) if decodedSignerCert == nil { return cert, errors.New("unable to decode certificate") } signerCert, err := x509.ParseCertificate(decodedSignerCert.Bytes) if err != nil { return cert, fmt.Errorf( "error parsing certificate: decodedSignerCert.Bytes: %s", err, ) } signerKey, err := parsePrivateKeyPEM(ca.Key) if err != nil { return cert, fmt.Errorf( "error parsing private key: %s", err, ) } template, err := getBaseCertTemplate(cn, ips, alternateDNS, daysValid) if err != nil { return cert, err } cert.Cert, cert.Key, err = getCertAndKey( template, priv, signerCert, signerKey, ) return cert, err } func getCertAndKey( template *x509.Certificate, signeeKey crypto.PrivateKey, parent *x509.Certificate, signingKey crypto.PrivateKey, ) (string, string, error) { signeePubKey, err := getPublicKey(signeeKey) if err != nil { return "", "", fmt.Errorf("error retrieving public key from signee key: %s", err) } derBytes, err := x509.CreateCertificate( rand.Reader, template, parent, signeePubKey, signingKey, ) if err != nil { return "", "", fmt.Errorf("error creating certificate: %s", err) } certBuffer := bytes.Buffer{} if err := pem.Encode( &certBuffer, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}, ); err != nil { return "", "", fmt.Errorf("error pem-encoding certificate: %s", err) } keyBuffer := bytes.Buffer{} if err := pem.Encode( &keyBuffer, pemBlockForKey(signeeKey), ); err != nil { return "", "", fmt.Errorf("error pem-encoding key: %s", err) } return certBuffer.String(), keyBuffer.String(), nil } func getBaseCertTemplate( cn string, ips []interface{}, alternateDNS []interface{}, daysValid int, ) (*x509.Certificate, error) { ipAddresses, err := getNetIPs(ips) if err != nil { return nil, err } dnsNames, err := getAlternateDNSStrs(alternateDNS) if err != nil { return nil, err } serialNumberUpperBound := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberUpperBound) if err != nil { return nil, err } return &x509.Certificate{ SerialNumber: serialNumber, Subject: pkix.Name{ CommonName: cn, }, IPAddresses: ipAddresses, DNSNames: dnsNames, NotBefore: time.Now(), NotAfter: time.Now().Add(time.Hour * 24 * time.Duration(daysValid)), KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{ x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth, }, BasicConstraintsValid: true, }, nil } func getNetIPs(ips []interface{}) ([]net.IP, error) { if ips == nil { return []net.IP{}, nil } var ipStr string var ok bool var netIP net.IP netIPs := make([]net.IP, len(ips)) for i, ip := range ips { ipStr, ok = ip.(string) if !ok { return nil, fmt.Errorf("error parsing ip: %v is not a string", ip) } netIP = net.ParseIP(ipStr) if netIP == nil { return nil, fmt.Errorf("error parsing ip: %s", ipStr) } netIPs[i] = netIP } return netIPs, nil } func getAlternateDNSStrs(alternateDNS []interface{}) ([]string, error) { if alternateDNS == nil { return []string{}, nil } var dnsStr string var ok bool alternateDNSStrs := make([]string, len(alternateDNS)) for i, dns := range alternateDNS { dnsStr, ok = dns.(string) if !ok { return nil, fmt.Errorf( "error processing alternate dns name: %v is not a string", dns, ) } alternateDNSStrs[i] = dnsStr } return alternateDNSStrs, nil } func encryptAES(password string, plaintext string) (string, error) { if plaintext == "" { return "", nil } key := make([]byte, 32) copy(key, []byte(password)) block, err := aes.NewCipher(key) if err != nil { return "", err } content := []byte(plaintext) blockSize := block.BlockSize() padding := blockSize - len(content)%blockSize padtext := bytes.Repeat([]byte{byte(padding)}, padding) content = append(content, padtext...) ciphertext := make([]byte, aes.BlockSize+len(content)) iv := ciphertext[:aes.BlockSize] if _, err := io.ReadFull(rand.Reader, iv); err != nil { return "", err } mode := cipher.NewCBCEncrypter(block, iv) mode.CryptBlocks(ciphertext[aes.BlockSize:], content) return base64.StdEncoding.EncodeToString(ciphertext), nil } func decryptAES(password string, crypt64 string) (string, error) { if crypt64 == "" { return "", nil } key := make([]byte, 32) copy(key, []byte(password)) crypt, err := base64.StdEncoding.DecodeString(crypt64) if err != nil { return "", err } block, err := aes.NewCipher(key) if err != nil { return "", err } iv := crypt[:aes.BlockSize] crypt = crypt[aes.BlockSize:] decrypted := make([]byte, len(crypt)) mode := cipher.NewCBCDecrypter(block, iv) mode.CryptBlocks(decrypted, crypt) return string(decrypted[:len(decrypted)-int(decrypted[len(decrypted)-1])]), nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/Masterminds/sprig/v3/dict.go
vendor/github.com/Masterminds/sprig/v3/dict.go
package sprig import ( "dario.cat/mergo" "github.com/mitchellh/copystructure" ) func get(d map[string]interface{}, key string) interface{} { if val, ok := d[key]; ok { return val } return "" } func set(d map[string]interface{}, key string, value interface{}) map[string]interface{} { d[key] = value return d } func unset(d map[string]interface{}, key string) map[string]interface{} { delete(d, key) return d } func hasKey(d map[string]interface{}, key string) bool { _, ok := d[key] return ok } func pluck(key string, d ...map[string]interface{}) []interface{} { res := []interface{}{} for _, dict := range d { if val, ok := dict[key]; ok { res = append(res, val) } } return res } func keys(dicts ...map[string]interface{}) []string { k := []string{} for _, dict := range dicts { for key := range dict { k = append(k, key) } } return k } func pick(dict map[string]interface{}, keys ...string) map[string]interface{} { res := map[string]interface{}{} for _, k := range keys { if v, ok := dict[k]; ok { res[k] = v } } return res } func omit(dict map[string]interface{}, keys ...string) map[string]interface{} { res := map[string]interface{}{} omit := make(map[string]bool, len(keys)) for _, k := range keys { omit[k] = true } for k, v := range dict { if _, ok := omit[k]; !ok { res[k] = v } } return res } func dict(v ...interface{}) map[string]interface{} { dict := map[string]interface{}{} lenv := len(v) for i := 0; i < lenv; i += 2 { key := strval(v[i]) if i+1 >= lenv { dict[key] = "" continue } dict[key] = v[i+1] } return dict } func merge(dst map[string]interface{}, srcs ...map[string]interface{}) interface{} { for _, src := range srcs { if err := mergo.Merge(&dst, src); err != nil { // Swallow errors inside of a template. return "" } } return dst } func mustMerge(dst map[string]interface{}, srcs ...map[string]interface{}) (interface{}, error) { for _, src := range srcs { if err := mergo.Merge(&dst, src); err != nil { return nil, err } } return dst, nil } func mergeOverwrite(dst map[string]interface{}, srcs ...map[string]interface{}) interface{} { for _, src := range srcs { if err := mergo.MergeWithOverwrite(&dst, src); err != nil { // Swallow errors inside of a template. return "" } } return dst } func mustMergeOverwrite(dst map[string]interface{}, srcs ...map[string]interface{}) (interface{}, error) { for _, src := range srcs { if err := mergo.MergeWithOverwrite(&dst, src); err != nil { return nil, err } } return dst, nil } func values(dict map[string]interface{}) []interface{} { values := []interface{}{} for _, value := range dict { values = append(values, value) } return values } func deepCopy(i interface{}) interface{} { c, err := mustDeepCopy(i) if err != nil { panic("deepCopy error: " + err.Error()) } return c } func mustDeepCopy(i interface{}) (interface{}, error) { return copystructure.Copy(i) } func dig(ps ...interface{}) (interface{}, error) { if len(ps) < 3 { panic("dig needs at least three arguments") } dict := ps[len(ps)-1].(map[string]interface{}) def := ps[len(ps)-2] ks := make([]string, len(ps)-2) for i := 0; i < len(ks); i++ { ks[i] = ps[i].(string) } return digFromDict(dict, def, ks) } func digFromDict(dict map[string]interface{}, d interface{}, ks []string) (interface{}, error) { k, ns := ks[0], ks[1:len(ks)] step, has := dict[k] if !has { return d, nil } if len(ns) == 0 { return step, nil } return digFromDict(step.(map[string]interface{}), d, ns) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/Masterminds/sprig/v3/regex.go
vendor/github.com/Masterminds/sprig/v3/regex.go
package sprig import ( "regexp" ) func regexMatch(regex string, s string) bool { match, _ := regexp.MatchString(regex, s) return match } func mustRegexMatch(regex string, s string) (bool, error) { return regexp.MatchString(regex, s) } func regexFindAll(regex string, s string, n int) []string { r := regexp.MustCompile(regex) return r.FindAllString(s, n) } func mustRegexFindAll(regex string, s string, n int) ([]string, error) { r, err := regexp.Compile(regex) if err != nil { return []string{}, err } return r.FindAllString(s, n), nil } func regexFind(regex string, s string) string { r := regexp.MustCompile(regex) return r.FindString(s) } func mustRegexFind(regex string, s string) (string, error) { r, err := regexp.Compile(regex) if err != nil { return "", err } return r.FindString(s), nil } func regexReplaceAll(regex string, s string, repl string) string { r := regexp.MustCompile(regex) return r.ReplaceAllString(s, repl) } func mustRegexReplaceAll(regex string, s string, repl string) (string, error) { r, err := regexp.Compile(regex) if err != nil { return "", err } return r.ReplaceAllString(s, repl), nil } func regexReplaceAllLiteral(regex string, s string, repl string) string { r := regexp.MustCompile(regex) return r.ReplaceAllLiteralString(s, repl) } func mustRegexReplaceAllLiteral(regex string, s string, repl string) (string, error) { r, err := regexp.Compile(regex) if err != nil { return "", err } return r.ReplaceAllLiteralString(s, repl), nil } func regexSplit(regex string, s string, n int) []string { r := regexp.MustCompile(regex) return r.Split(s, n) } func mustRegexSplit(regex string, s string, n int) ([]string, error) { r, err := regexp.Compile(regex) if err != nil { return []string{}, err } return r.Split(s, n), nil } func regexQuoteMeta(s string) string { return regexp.QuoteMeta(s) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/Masterminds/sprig/v3/numeric.go
vendor/github.com/Masterminds/sprig/v3/numeric.go
package sprig import ( "fmt" "math" "strconv" "strings" "github.com/spf13/cast" "github.com/shopspring/decimal" ) // toFloat64 converts 64-bit floats func toFloat64(v interface{}) float64 { return cast.ToFloat64(v) } func toInt(v interface{}) int { return cast.ToInt(v) } // toInt64 converts integer types to 64-bit integers func toInt64(v interface{}) int64 { return cast.ToInt64(v) } func max(a interface{}, i ...interface{}) int64 { aa := toInt64(a) for _, b := range i { bb := toInt64(b) if bb > aa { aa = bb } } return aa } func maxf(a interface{}, i ...interface{}) float64 { aa := toFloat64(a) for _, b := range i { bb := toFloat64(b) aa = math.Max(aa, bb) } return aa } func min(a interface{}, i ...interface{}) int64 { aa := toInt64(a) for _, b := range i { bb := toInt64(b) if bb < aa { aa = bb } } return aa } func minf(a interface{}, i ...interface{}) float64 { aa := toFloat64(a) for _, b := range i { bb := toFloat64(b) aa = math.Min(aa, bb) } return aa } func until(count int) []int { step := 1 if count < 0 { step = -1 } return untilStep(0, count, step) } func untilStep(start, stop, step int) []int { v := []int{} if stop < start { if step >= 0 { return v } for i := start; i > stop; i += step { v = append(v, i) } return v } if step <= 0 { return v } for i := start; i < stop; i += step { v = append(v, i) } return v } func floor(a interface{}) float64 { aa := toFloat64(a) return math.Floor(aa) } func ceil(a interface{}) float64 { aa := toFloat64(a) return math.Ceil(aa) } func round(a interface{}, p int, rOpt ...float64) float64 { roundOn := .5 if len(rOpt) > 0 { roundOn = rOpt[0] } val := toFloat64(a) places := toFloat64(p) var round float64 pow := math.Pow(10, places) digit := pow * val _, div := math.Modf(digit) if div >= roundOn { round = math.Ceil(digit) } else { round = math.Floor(digit) } return round / pow } // converts unix octal to decimal func toDecimal(v interface{}) int64 { result, err := strconv.ParseInt(fmt.Sprint(v), 8, 64) if err != nil { return 0 } return result } func seq(params ...int) string { increment := 1 switch len(params) { case 0: return "" case 1: start := 1 end := params[0] if end < start { increment = -1 } return intArrayToString(untilStep(start, end+increment, increment), " ") case 3: start := params[0] end := params[2] step := params[1] if end < start { increment = -1 if step > 0 { return "" } } return intArrayToString(untilStep(start, end+increment, step), " ") case 2: start := params[0] end := params[1] step := 1 if end < start { step = -1 } return intArrayToString(untilStep(start, end+step, step), " ") default: return "" } } func intArrayToString(slice []int, delimeter string) string { return strings.Trim(strings.Join(strings.Fields(fmt.Sprint(slice)), delimeter), "[]") } // performs a float and subsequent decimal.Decimal conversion on inputs, // and iterates through a and b executing the mathmetical operation f func execDecimalOp(a interface{}, b []interface{}, f func(d1, d2 decimal.Decimal) decimal.Decimal) float64 { prt := decimal.NewFromFloat(toFloat64(a)) for _, x := range b { dx := decimal.NewFromFloat(toFloat64(x)) prt = f(prt, dx) } rslt, _ := prt.Float64() return rslt }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/Masterminds/sprig/v3/functions.go
vendor/github.com/Masterminds/sprig/v3/functions.go
package sprig import ( "errors" "html/template" "math/rand" "os" "path" "path/filepath" "reflect" "strconv" "strings" ttemplate "text/template" "time" util "github.com/Masterminds/goutils" "github.com/huandu/xstrings" "github.com/shopspring/decimal" ) // FuncMap produces the function map. // // Use this to pass the functions into the template engine: // // tpl := template.New("foo").Funcs(sprig.FuncMap())) func FuncMap() template.FuncMap { return HtmlFuncMap() } // HermeticTxtFuncMap returns a 'text/template'.FuncMap with only repeatable functions. func HermeticTxtFuncMap() ttemplate.FuncMap { r := TxtFuncMap() for _, name := range nonhermeticFunctions { delete(r, name) } return r } // HermeticHtmlFuncMap returns an 'html/template'.Funcmap with only repeatable functions. func HermeticHtmlFuncMap() template.FuncMap { r := HtmlFuncMap() for _, name := range nonhermeticFunctions { delete(r, name) } return r } // TxtFuncMap returns a 'text/template'.FuncMap func TxtFuncMap() ttemplate.FuncMap { return ttemplate.FuncMap(GenericFuncMap()) } // HtmlFuncMap returns an 'html/template'.Funcmap func HtmlFuncMap() template.FuncMap { return template.FuncMap(GenericFuncMap()) } // GenericFuncMap returns a copy of the basic function map as a map[string]interface{}. func GenericFuncMap() map[string]interface{} { gfm := make(map[string]interface{}, len(genericMap)) for k, v := range genericMap { gfm[k] = v } return gfm } // These functions are not guaranteed to evaluate to the same result for given input, because they // refer to the environment or global state. var nonhermeticFunctions = []string{ // Date functions "date", "date_in_zone", "date_modify", "now", "htmlDate", "htmlDateInZone", "dateInZone", "dateModify", // Strings "randAlphaNum", "randAlpha", "randAscii", "randNumeric", "randBytes", "uuidv4", // OS "env", "expandenv", // Network "getHostByName", } var genericMap = map[string]interface{}{ "hello": func() string { return "Hello!" }, // Date functions "ago": dateAgo, "date": date, "date_in_zone": dateInZone, "date_modify": dateModify, "dateInZone": dateInZone, "dateModify": dateModify, "duration": duration, "durationRound": durationRound, "htmlDate": htmlDate, "htmlDateInZone": htmlDateInZone, "must_date_modify": mustDateModify, "mustDateModify": mustDateModify, "mustToDate": mustToDate, "now": time.Now, "toDate": toDate, "unixEpoch": unixEpoch, // Strings "abbrev": abbrev, "abbrevboth": abbrevboth, "trunc": trunc, "trim": strings.TrimSpace, "upper": strings.ToUpper, "lower": strings.ToLower, "title": strings.Title, "untitle": untitle, "substr": substring, // Switch order so that "foo" | repeat 5 "repeat": func(count int, str string) string { return strings.Repeat(str, count) }, // Deprecated: Use trimAll. "trimall": func(a, b string) string { return strings.Trim(b, a) }, // Switch order so that "$foo" | trimall "$" "trimAll": func(a, b string) string { return strings.Trim(b, a) }, "trimSuffix": func(a, b string) string { return strings.TrimSuffix(b, a) }, "trimPrefix": func(a, b string) string { return strings.TrimPrefix(b, a) }, "nospace": util.DeleteWhiteSpace, "initials": initials, "randAlphaNum": randAlphaNumeric, "randAlpha": randAlpha, "randAscii": randAscii, "randNumeric": randNumeric, "swapcase": util.SwapCase, "shuffle": xstrings.Shuffle, "snakecase": xstrings.ToSnakeCase, // camelcase used to call xstrings.ToCamelCase, but that function had a breaking change in version // 1.5 that moved it from upper camel case to lower camel case. This is a breaking change for sprig. // A new xstrings.ToPascalCase function was added that provided upper camel case. "camelcase": xstrings.ToPascalCase, "kebabcase": xstrings.ToKebabCase, "wrap": func(l int, s string) string { return util.Wrap(s, l) }, "wrapWith": func(l int, sep, str string) string { return util.WrapCustom(str, l, sep, true) }, // Switch order so that "foobar" | contains "foo" "contains": func(substr string, str string) bool { return strings.Contains(str, substr) }, "hasPrefix": func(substr string, str string) bool { return strings.HasPrefix(str, substr) }, "hasSuffix": func(substr string, str string) bool { return strings.HasSuffix(str, substr) }, "quote": quote, "squote": squote, "cat": cat, "indent": indent, "nindent": nindent, "replace": replace, "plural": plural, "sha1sum": sha1sum, "sha256sum": sha256sum, "sha512sum": sha512sum, "adler32sum": adler32sum, "toString": strval, // Wrap Atoi to stop errors. "atoi": func(a string) int { i, _ := strconv.Atoi(a); return i }, "int64": toInt64, "int": toInt, "float64": toFloat64, "seq": seq, "toDecimal": toDecimal, //"gt": func(a, b int) bool {return a > b}, //"gte": func(a, b int) bool {return a >= b}, //"lt": func(a, b int) bool {return a < b}, //"lte": func(a, b int) bool {return a <= b}, // split "/" foo/bar returns map[int]string{0: foo, 1: bar} "split": split, "splitList": func(sep, orig string) []string { return strings.Split(orig, sep) }, // splitn "/" foo/bar/fuu returns map[int]string{0: foo, 1: bar/fuu} "splitn": splitn, "toStrings": strslice, "until": until, "untilStep": untilStep, // VERY basic arithmetic. "add1": func(i interface{}) int64 { return toInt64(i) + 1 }, "add": func(i ...interface{}) int64 { var a int64 = 0 for _, b := range i { a += toInt64(b) } return a }, "sub": func(a, b interface{}) int64 { return toInt64(a) - toInt64(b) }, "div": func(a, b interface{}) int64 { return toInt64(a) / toInt64(b) }, "mod": func(a, b interface{}) int64 { return toInt64(a) % toInt64(b) }, "mul": func(a interface{}, v ...interface{}) int64 { val := toInt64(a) for _, b := range v { val = val * toInt64(b) } return val }, "randInt": func(min, max int) int { return rand.Intn(max-min) + min }, "add1f": func(i interface{}) float64 { return execDecimalOp(i, []interface{}{1}, func(d1, d2 decimal.Decimal) decimal.Decimal { return d1.Add(d2) }) }, "addf": func(i ...interface{}) float64 { a := interface{}(float64(0)) return execDecimalOp(a, i, func(d1, d2 decimal.Decimal) decimal.Decimal { return d1.Add(d2) }) }, "subf": func(a interface{}, v ...interface{}) float64 { return execDecimalOp(a, v, func(d1, d2 decimal.Decimal) decimal.Decimal { return d1.Sub(d2) }) }, "divf": func(a interface{}, v ...interface{}) float64 { return execDecimalOp(a, v, func(d1, d2 decimal.Decimal) decimal.Decimal { return d1.Div(d2) }) }, "mulf": func(a interface{}, v ...interface{}) float64 { return execDecimalOp(a, v, func(d1, d2 decimal.Decimal) decimal.Decimal { return d1.Mul(d2) }) }, "biggest": max, "max": max, "min": min, "maxf": maxf, "minf": minf, "ceil": ceil, "floor": floor, "round": round, // string slices. Note that we reverse the order b/c that's better // for template processing. "join": join, "sortAlpha": sortAlpha, // Defaults "default": dfault, "empty": empty, "coalesce": coalesce, "all": all, "any": any, "compact": compact, "mustCompact": mustCompact, "fromJson": fromJson, "toJson": toJson, "toPrettyJson": toPrettyJson, "toRawJson": toRawJson, "mustFromJson": mustFromJson, "mustToJson": mustToJson, "mustToPrettyJson": mustToPrettyJson, "mustToRawJson": mustToRawJson, "ternary": ternary, "deepCopy": deepCopy, "mustDeepCopy": mustDeepCopy, // Reflection "typeOf": typeOf, "typeIs": typeIs, "typeIsLike": typeIsLike, "kindOf": kindOf, "kindIs": kindIs, "deepEqual": reflect.DeepEqual, // OS: "env": os.Getenv, "expandenv": os.ExpandEnv, // Network: "getHostByName": getHostByName, // Paths: "base": path.Base, "dir": path.Dir, "clean": path.Clean, "ext": path.Ext, "isAbs": path.IsAbs, // Filepaths: "osBase": filepath.Base, "osClean": filepath.Clean, "osDir": filepath.Dir, "osExt": filepath.Ext, "osIsAbs": filepath.IsAbs, // Encoding: "b64enc": base64encode, "b64dec": base64decode, "b32enc": base32encode, "b32dec": base32decode, // Data Structures: "tuple": list, // FIXME: with the addition of append/prepend these are no longer immutable. "list": list, "dict": dict, "get": get, "set": set, "unset": unset, "hasKey": hasKey, "pluck": pluck, "keys": keys, "pick": pick, "omit": omit, "merge": merge, "mergeOverwrite": mergeOverwrite, "mustMerge": mustMerge, "mustMergeOverwrite": mustMergeOverwrite, "values": values, "append": push, "push": push, "mustAppend": mustPush, "mustPush": mustPush, "prepend": prepend, "mustPrepend": mustPrepend, "first": first, "mustFirst": mustFirst, "rest": rest, "mustRest": mustRest, "last": last, "mustLast": mustLast, "initial": initial, "mustInitial": mustInitial, "reverse": reverse, "mustReverse": mustReverse, "uniq": uniq, "mustUniq": mustUniq, "without": without, "mustWithout": mustWithout, "has": has, "mustHas": mustHas, "slice": slice, "mustSlice": mustSlice, "concat": concat, "dig": dig, "chunk": chunk, "mustChunk": mustChunk, // Crypto: "bcrypt": bcrypt, "htpasswd": htpasswd, "genPrivateKey": generatePrivateKey, "derivePassword": derivePassword, "buildCustomCert": buildCustomCertificate, "genCA": generateCertificateAuthority, "genCAWithKey": generateCertificateAuthorityWithPEMKey, "genSelfSignedCert": generateSelfSignedCertificate, "genSelfSignedCertWithKey": generateSelfSignedCertificateWithPEMKey, "genSignedCert": generateSignedCertificate, "genSignedCertWithKey": generateSignedCertificateWithPEMKey, "encryptAES": encryptAES, "decryptAES": decryptAES, "randBytes": randBytes, // UUIDs: "uuidv4": uuidv4, // SemVer: "semver": semver, "semverCompare": semverCompare, // Flow Control: "fail": func(msg string) (string, error) { return "", errors.New(msg) }, // Regex "regexMatch": regexMatch, "mustRegexMatch": mustRegexMatch, "regexFindAll": regexFindAll, "mustRegexFindAll": mustRegexFindAll, "regexFind": regexFind, "mustRegexFind": mustRegexFind, "regexReplaceAll": regexReplaceAll, "mustRegexReplaceAll": mustRegexReplaceAll, "regexReplaceAllLiteral": regexReplaceAllLiteral, "mustRegexReplaceAllLiteral": mustRegexReplaceAllLiteral, "regexSplit": regexSplit, "mustRegexSplit": mustRegexSplit, "regexQuoteMeta": regexQuoteMeta, // URLs: "urlParse": urlParse, "urlJoin": urlJoin, }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/Masterminds/sprig/v3/doc.go
vendor/github.com/Masterminds/sprig/v3/doc.go
/* Package sprig provides template functions for Go. This package contains a number of utility functions for working with data inside of Go `html/template` and `text/template` files. To add these functions, use the `template.Funcs()` method: t := template.New("foo").Funcs(sprig.FuncMap()) Note that you should add the function map before you parse any template files. In several cases, Sprig reverses the order of arguments from the way they appear in the standard library. This is to make it easier to pipe arguments into functions. See http://masterminds.github.io/sprig/ for more detailed documentation on each of the available functions. */ package sprig
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/Masterminds/sprig/v3/semver.go
vendor/github.com/Masterminds/sprig/v3/semver.go
package sprig import ( sv2 "github.com/Masterminds/semver/v3" ) func semverCompare(constraint, version string) (bool, error) { c, err := sv2.NewConstraint(constraint) if err != nil { return false, err } v, err := sv2.NewVersion(version) if err != nil { return false, err } return c.Check(v), nil } func semver(version string) (*sv2.Version, error) { return sv2.NewVersion(version) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/Masterminds/semver/v3/collection.go
vendor/github.com/Masterminds/semver/v3/collection.go
package semver // Collection is a collection of Version instances and implements the sort // interface. See the sort package for more details. // https://golang.org/pkg/sort/ type Collection []*Version // Len returns the length of a collection. The number of Version instances // on the slice. func (c Collection) Len() int { return len(c) } // Less is needed for the sort interface to compare two Version objects on the // slice. If checks if one is less than the other. func (c Collection) Less(i, j int) bool { return c[i].LessThan(c[j]) } // Swap is needed for the sort interface to replace the Version objects // at two different positions in the slice. func (c Collection) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/Masterminds/semver/v3/constraints.go
vendor/github.com/Masterminds/semver/v3/constraints.go
package semver import ( "bytes" "errors" "fmt" "regexp" "strings" ) // Constraints is one or more constraint that a semantic version can be // checked against. type Constraints struct { constraints [][]*constraint } // NewConstraint returns a Constraints instance that a Version instance can // be checked against. If there is a parse error it will be returned. func NewConstraint(c string) (*Constraints, error) { // Rewrite - ranges into a comparison operation. c = rewriteRange(c) ors := strings.Split(c, "||") or := make([][]*constraint, len(ors)) for k, v := range ors { // TODO: Find a way to validate and fetch all the constraints in a simpler form // Validate the segment if !validConstraintRegex.MatchString(v) { return nil, fmt.Errorf("improper constraint: %s", v) } cs := findConstraintRegex.FindAllString(v, -1) if cs == nil { cs = append(cs, v) } result := make([]*constraint, len(cs)) for i, s := range cs { pc, err := parseConstraint(s) if err != nil { return nil, err } result[i] = pc } or[k] = result } o := &Constraints{constraints: or} return o, nil } // Check tests if a version satisfies the constraints. func (cs Constraints) Check(v *Version) bool { // TODO(mattfarina): For v4 of this library consolidate the Check and Validate // functions as the underlying functions make that possible now. // loop over the ORs and check the inner ANDs for _, o := range cs.constraints { joy := true for _, c := range o { if check, _ := c.check(v); !check { joy = false break } } if joy { return true } } return false } // Validate checks if a version satisfies a constraint. If not a slice of // reasons for the failure are returned in addition to a bool. func (cs Constraints) Validate(v *Version) (bool, []error) { // loop over the ORs and check the inner ANDs var e []error // Capture the prerelease message only once. When it happens the first time // this var is marked var prerelesase bool for _, o := range cs.constraints { joy := true for _, c := range o { // Before running the check handle the case there the version is // a prerelease and the check is not searching for prereleases. if c.con.pre == "" && v.pre != "" { if !prerelesase { em := fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) e = append(e, em) prerelesase = true } joy = false } else { if _, err := c.check(v); err != nil { e = append(e, err) joy = false } } } if joy { return true, []error{} } } return false, e } func (cs Constraints) String() string { buf := make([]string, len(cs.constraints)) var tmp bytes.Buffer for k, v := range cs.constraints { tmp.Reset() vlen := len(v) for kk, c := range v { tmp.WriteString(c.string()) // Space separate the AND conditions if vlen > 1 && kk < vlen-1 { tmp.WriteString(" ") } } buf[k] = tmp.String() } return strings.Join(buf, " || ") } // UnmarshalText implements the encoding.TextUnmarshaler interface. func (cs *Constraints) UnmarshalText(text []byte) error { temp, err := NewConstraint(string(text)) if err != nil { return err } *cs = *temp return nil } // MarshalText implements the encoding.TextMarshaler interface. func (cs Constraints) MarshalText() ([]byte, error) { return []byte(cs.String()), nil } var constraintOps map[string]cfunc var constraintRegex *regexp.Regexp var constraintRangeRegex *regexp.Regexp // Used to find individual constraints within a multi-constraint string var findConstraintRegex *regexp.Regexp // Used to validate an segment of ANDs is valid var validConstraintRegex *regexp.Regexp const cvRegex string = `v?([0-9|x|X|\*]+)(\.[0-9|x|X|\*]+)?(\.[0-9|x|X|\*]+)?` + `(-([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` + `(\+([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` func init() { constraintOps = map[string]cfunc{ "": constraintTildeOrEqual, "=": constraintTildeOrEqual, "!=": constraintNotEqual, ">": constraintGreaterThan, "<": constraintLessThan, ">=": constraintGreaterThanEqual, "=>": constraintGreaterThanEqual, "<=": constraintLessThanEqual, "=<": constraintLessThanEqual, "~": constraintTilde, "~>": constraintTilde, "^": constraintCaret, } ops := `=||!=|>|<|>=|=>|<=|=<|~|~>|\^` constraintRegex = regexp.MustCompile(fmt.Sprintf( `^\s*(%s)\s*(%s)\s*$`, ops, cvRegex)) constraintRangeRegex = regexp.MustCompile(fmt.Sprintf( `\s*(%s)\s+-\s+(%s)\s*`, cvRegex, cvRegex)) findConstraintRegex = regexp.MustCompile(fmt.Sprintf( `(%s)\s*(%s)`, ops, cvRegex)) // The first time a constraint shows up will look slightly different from // future times it shows up due to a leading space or comma in a given // string. validConstraintRegex = regexp.MustCompile(fmt.Sprintf( `^(\s*(%s)\s*(%s)\s*)((?:\s+|,\s*)(%s)\s*(%s)\s*)*$`, ops, cvRegex, ops, cvRegex)) } // An individual constraint type constraint struct { // The version used in the constraint check. For example, if a constraint // is '<= 2.0.0' the con a version instance representing 2.0.0. con *Version // The original parsed version (e.g., 4.x from != 4.x) orig string // The original operator for the constraint origfunc string // When an x is used as part of the version (e.g., 1.x) minorDirty bool dirty bool patchDirty bool } // Check if a version meets the constraint func (c *constraint) check(v *Version) (bool, error) { return constraintOps[c.origfunc](v, c) } // String prints an individual constraint into a string func (c *constraint) string() string { return c.origfunc + c.orig } type cfunc func(v *Version, c *constraint) (bool, error) func parseConstraint(c string) (*constraint, error) { if len(c) > 0 { m := constraintRegex.FindStringSubmatch(c) if m == nil { return nil, fmt.Errorf("improper constraint: %s", c) } cs := &constraint{ orig: m[2], origfunc: m[1], } ver := m[2] minorDirty := false patchDirty := false dirty := false if isX(m[3]) || m[3] == "" { ver = fmt.Sprintf("0.0.0%s", m[6]) dirty = true } else if isX(strings.TrimPrefix(m[4], ".")) || m[4] == "" { minorDirty = true dirty = true ver = fmt.Sprintf("%s.0.0%s", m[3], m[6]) } else if isX(strings.TrimPrefix(m[5], ".")) || m[5] == "" { dirty = true patchDirty = true ver = fmt.Sprintf("%s%s.0%s", m[3], m[4], m[6]) } con, err := NewVersion(ver) if err != nil { // The constraintRegex should catch any regex parsing errors. So, // we should never get here. return nil, errors.New("constraint Parser Error") } cs.con = con cs.minorDirty = minorDirty cs.patchDirty = patchDirty cs.dirty = dirty return cs, nil } // The rest is the special case where an empty string was passed in which // is equivalent to * or >=0.0.0 con, err := StrictNewVersion("0.0.0") if err != nil { // The constraintRegex should catch any regex parsing errors. So, // we should never get here. return nil, errors.New("constraint Parser Error") } cs := &constraint{ con: con, orig: c, origfunc: "", minorDirty: false, patchDirty: false, dirty: true, } return cs, nil } // Constraint functions func constraintNotEqual(v *Version, c *constraint) (bool, error) { if c.dirty { // If there is a pre-release on the version but the constraint isn't looking // for them assume that pre-releases are not compatible. See issue 21 for // more details. if v.Prerelease() != "" && c.con.Prerelease() == "" { return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) } if c.con.Major() != v.Major() { return true, nil } if c.con.Minor() != v.Minor() && !c.minorDirty { return true, nil } else if c.minorDirty { return false, fmt.Errorf("%s is equal to %s", v, c.orig) } else if c.con.Patch() != v.Patch() && !c.patchDirty { return true, nil } else if c.patchDirty { // Need to handle prereleases if present if v.Prerelease() != "" || c.con.Prerelease() != "" { eq := comparePrerelease(v.Prerelease(), c.con.Prerelease()) != 0 if eq { return true, nil } return false, fmt.Errorf("%s is equal to %s", v, c.orig) } return false, fmt.Errorf("%s is equal to %s", v, c.orig) } } eq := v.Equal(c.con) if eq { return false, fmt.Errorf("%s is equal to %s", v, c.orig) } return true, nil } func constraintGreaterThan(v *Version, c *constraint) (bool, error) { // If there is a pre-release on the version but the constraint isn't looking // for them assume that pre-releases are not compatible. See issue 21 for // more details. if v.Prerelease() != "" && c.con.Prerelease() == "" { return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) } var eq bool if !c.dirty { eq = v.Compare(c.con) == 1 if eq { return true, nil } return false, fmt.Errorf("%s is less than or equal to %s", v, c.orig) } if v.Major() > c.con.Major() { return true, nil } else if v.Major() < c.con.Major() { return false, fmt.Errorf("%s is less than or equal to %s", v, c.orig) } else if c.minorDirty { // This is a range case such as >11. When the version is something like // 11.1.0 is it not > 11. For that we would need 12 or higher return false, fmt.Errorf("%s is less than or equal to %s", v, c.orig) } else if c.patchDirty { // This is for ranges such as >11.1. A version of 11.1.1 is not greater // which one of 11.2.1 is greater eq = v.Minor() > c.con.Minor() if eq { return true, nil } return false, fmt.Errorf("%s is less than or equal to %s", v, c.orig) } // If we have gotten here we are not comparing pre-preleases and can use the // Compare function to accomplish that. eq = v.Compare(c.con) == 1 if eq { return true, nil } return false, fmt.Errorf("%s is less than or equal to %s", v, c.orig) } func constraintLessThan(v *Version, c *constraint) (bool, error) { // If there is a pre-release on the version but the constraint isn't looking // for them assume that pre-releases are not compatible. See issue 21 for // more details. if v.Prerelease() != "" && c.con.Prerelease() == "" { return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) } eq := v.Compare(c.con) < 0 if eq { return true, nil } return false, fmt.Errorf("%s is greater than or equal to %s", v, c.orig) } func constraintGreaterThanEqual(v *Version, c *constraint) (bool, error) { // If there is a pre-release on the version but the constraint isn't looking // for them assume that pre-releases are not compatible. See issue 21 for // more details. if v.Prerelease() != "" && c.con.Prerelease() == "" { return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) } eq := v.Compare(c.con) >= 0 if eq { return true, nil } return false, fmt.Errorf("%s is less than %s", v, c.orig) } func constraintLessThanEqual(v *Version, c *constraint) (bool, error) { // If there is a pre-release on the version but the constraint isn't looking // for them assume that pre-releases are not compatible. See issue 21 for // more details. if v.Prerelease() != "" && c.con.Prerelease() == "" { return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) } var eq bool if !c.dirty { eq = v.Compare(c.con) <= 0 if eq { return true, nil } return false, fmt.Errorf("%s is greater than %s", v, c.orig) } if v.Major() > c.con.Major() { return false, fmt.Errorf("%s is greater than %s", v, c.orig) } else if v.Major() == c.con.Major() && v.Minor() > c.con.Minor() && !c.minorDirty { return false, fmt.Errorf("%s is greater than %s", v, c.orig) } return true, nil } // ~*, ~>* --> >= 0.0.0 (any) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0, <3.0.0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0, <2.1.0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0, <1.3.0 // ~1.2.3, ~>1.2.3 --> >=1.2.3, <1.3.0 // ~1.2.0, ~>1.2.0 --> >=1.2.0, <1.3.0 func constraintTilde(v *Version, c *constraint) (bool, error) { // If there is a pre-release on the version but the constraint isn't looking // for them assume that pre-releases are not compatible. See issue 21 for // more details. if v.Prerelease() != "" && c.con.Prerelease() == "" { return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) } if v.LessThan(c.con) { return false, fmt.Errorf("%s is less than %s", v, c.orig) } // ~0.0.0 is a special case where all constraints are accepted. It's // equivalent to >= 0.0.0. if c.con.Major() == 0 && c.con.Minor() == 0 && c.con.Patch() == 0 && !c.minorDirty && !c.patchDirty { return true, nil } if v.Major() != c.con.Major() { return false, fmt.Errorf("%s does not have same major version as %s", v, c.orig) } if v.Minor() != c.con.Minor() && !c.minorDirty { return false, fmt.Errorf("%s does not have same major and minor version as %s", v, c.orig) } return true, nil } // When there is a .x (dirty) status it automatically opts in to ~. Otherwise // it's a straight = func constraintTildeOrEqual(v *Version, c *constraint) (bool, error) { // If there is a pre-release on the version but the constraint isn't looking // for them assume that pre-releases are not compatible. See issue 21 for // more details. if v.Prerelease() != "" && c.con.Prerelease() == "" { return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) } if c.dirty { return constraintTilde(v, c) } eq := v.Equal(c.con) if eq { return true, nil } return false, fmt.Errorf("%s is not equal to %s", v, c.orig) } // ^* --> (any) // ^1.2.3 --> >=1.2.3 <2.0.0 // ^1.2 --> >=1.2.0 <2.0.0 // ^1 --> >=1.0.0 <2.0.0 // ^0.2.3 --> >=0.2.3 <0.3.0 // ^0.2 --> >=0.2.0 <0.3.0 // ^0.0.3 --> >=0.0.3 <0.0.4 // ^0.0 --> >=0.0.0 <0.1.0 // ^0 --> >=0.0.0 <1.0.0 func constraintCaret(v *Version, c *constraint) (bool, error) { // If there is a pre-release on the version but the constraint isn't looking // for them assume that pre-releases are not compatible. See issue 21 for // more details. if v.Prerelease() != "" && c.con.Prerelease() == "" { return false, fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v) } // This less than handles prereleases if v.LessThan(c.con) { return false, fmt.Errorf("%s is less than %s", v, c.orig) } var eq bool // ^ when the major > 0 is >=x.y.z < x+1 if c.con.Major() > 0 || c.minorDirty { // ^ has to be within a major range for > 0. Everything less than was // filtered out with the LessThan call above. This filters out those // that greater but not within the same major range. eq = v.Major() == c.con.Major() if eq { return true, nil } return false, fmt.Errorf("%s does not have same major version as %s", v, c.orig) } // ^ when the major is 0 and minor > 0 is >=0.y.z < 0.y+1 if c.con.Major() == 0 && v.Major() > 0 { return false, fmt.Errorf("%s does not have same major version as %s", v, c.orig) } // If the con Minor is > 0 it is not dirty if c.con.Minor() > 0 || c.patchDirty { eq = v.Minor() == c.con.Minor() if eq { return true, nil } return false, fmt.Errorf("%s does not have same minor version as %s. Expected minor versions to match when constraint major version is 0", v, c.orig) } // ^ when the minor is 0 and minor > 0 is =0.0.z if c.con.Minor() == 0 && v.Minor() > 0 { return false, fmt.Errorf("%s does not have same minor version as %s", v, c.orig) } // At this point the major is 0 and the minor is 0 and not dirty. The patch // is not dirty so we need to check if they are equal. If they are not equal eq = c.con.Patch() == v.Patch() if eq { return true, nil } return false, fmt.Errorf("%s does not equal %s. Expect version and constraint to equal when major and minor versions are 0", v, c.orig) } func isX(x string) bool { switch x { case "x", "*", "X": return true default: return false } } func rewriteRange(i string) string { m := constraintRangeRegex.FindAllStringSubmatch(i, -1) if m == nil { return i } o := i for _, v := range m { t := fmt.Sprintf(">= %s, <= %s ", v[1], v[11]) o = strings.Replace(o, v[0], t, 1) } return o }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/Masterminds/semver/v3/version.go
vendor/github.com/Masterminds/semver/v3/version.go
package semver import ( "bytes" "database/sql/driver" "encoding/json" "errors" "fmt" "regexp" "strconv" "strings" ) // The compiled version of the regex created at init() is cached here so it // only needs to be created once. var versionRegex *regexp.Regexp var ( // ErrInvalidSemVer is returned a version is found to be invalid when // being parsed. ErrInvalidSemVer = errors.New("Invalid Semantic Version") // ErrEmptyString is returned when an empty string is passed in for parsing. ErrEmptyString = errors.New("Version string empty") // ErrInvalidCharacters is returned when invalid characters are found as // part of a version ErrInvalidCharacters = errors.New("Invalid characters in version") // ErrSegmentStartsZero is returned when a version segment starts with 0. // This is invalid in SemVer. ErrSegmentStartsZero = errors.New("Version segment starts with 0") // ErrInvalidMetadata is returned when the metadata is an invalid format ErrInvalidMetadata = errors.New("Invalid Metadata string") // ErrInvalidPrerelease is returned when the pre-release is an invalid format ErrInvalidPrerelease = errors.New("Invalid Prerelease string") ) // semVerRegex is the regular expression used to parse a semantic version. const semVerRegex string = `v?([0-9]+)(\.[0-9]+)?(\.[0-9]+)?` + `(-([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` + `(\+([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` // Version represents a single semantic version. type Version struct { major, minor, patch uint64 pre string metadata string original string } func init() { versionRegex = regexp.MustCompile("^" + semVerRegex + "$") } const ( num string = "0123456789" allowed string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-" + num ) // StrictNewVersion parses a given version and returns an instance of Version or // an error if unable to parse the version. Only parses valid semantic versions. // Performs checking that can find errors within the version. // If you want to coerce a version such as 1 or 1.2 and parse it as the 1.x // releases of semver did, use the NewVersion() function. func StrictNewVersion(v string) (*Version, error) { // Parsing here does not use RegEx in order to increase performance and reduce // allocations. if len(v) == 0 { return nil, ErrEmptyString } // Split the parts into [0]major, [1]minor, and [2]patch,prerelease,build parts := strings.SplitN(v, ".", 3) if len(parts) != 3 { return nil, ErrInvalidSemVer } sv := &Version{ original: v, } // Extract build metadata if strings.Contains(parts[2], "+") { extra := strings.SplitN(parts[2], "+", 2) sv.metadata = extra[1] parts[2] = extra[0] if err := validateMetadata(sv.metadata); err != nil { return nil, err } } // Extract build prerelease if strings.Contains(parts[2], "-") { extra := strings.SplitN(parts[2], "-", 2) sv.pre = extra[1] parts[2] = extra[0] if err := validatePrerelease(sv.pre); err != nil { return nil, err } } // Validate the number segments are valid. This includes only having positive // numbers and no leading 0's. for _, p := range parts { if !containsOnly(p, num) { return nil, ErrInvalidCharacters } if len(p) > 1 && p[0] == '0' { return nil, ErrSegmentStartsZero } } // Extract major, minor, and patch var err error sv.major, err = strconv.ParseUint(parts[0], 10, 64) if err != nil { return nil, err } sv.minor, err = strconv.ParseUint(parts[1], 10, 64) if err != nil { return nil, err } sv.patch, err = strconv.ParseUint(parts[2], 10, 64) if err != nil { return nil, err } return sv, nil } // NewVersion parses a given version and returns an instance of Version or // an error if unable to parse the version. If the version is SemVer-ish it // attempts to convert it to SemVer. If you want to validate it was a strict // semantic version at parse time see StrictNewVersion(). func NewVersion(v string) (*Version, error) { m := versionRegex.FindStringSubmatch(v) if m == nil { return nil, ErrInvalidSemVer } sv := &Version{ metadata: m[8], pre: m[5], original: v, } var err error sv.major, err = strconv.ParseUint(m[1], 10, 64) if err != nil { return nil, fmt.Errorf("Error parsing version segment: %s", err) } if m[2] != "" { sv.minor, err = strconv.ParseUint(strings.TrimPrefix(m[2], "."), 10, 64) if err != nil { return nil, fmt.Errorf("Error parsing version segment: %s", err) } } else { sv.minor = 0 } if m[3] != "" { sv.patch, err = strconv.ParseUint(strings.TrimPrefix(m[3], "."), 10, 64) if err != nil { return nil, fmt.Errorf("Error parsing version segment: %s", err) } } else { sv.patch = 0 } // Perform some basic due diligence on the extra parts to ensure they are // valid. if sv.pre != "" { if err = validatePrerelease(sv.pre); err != nil { return nil, err } } if sv.metadata != "" { if err = validateMetadata(sv.metadata); err != nil { return nil, err } } return sv, nil } // New creates a new instance of Version with each of the parts passed in as // arguments instead of parsing a version string. func New(major, minor, patch uint64, pre, metadata string) *Version { v := Version{ major: major, minor: minor, patch: patch, pre: pre, metadata: metadata, original: "", } v.original = v.String() return &v } // MustParse parses a given version and panics on error. func MustParse(v string) *Version { sv, err := NewVersion(v) if err != nil { panic(err) } return sv } // String converts a Version object to a string. // Note, if the original version contained a leading v this version will not. // See the Original() method to retrieve the original value. Semantic Versions // don't contain a leading v per the spec. Instead it's optional on // implementation. func (v Version) String() string { var buf bytes.Buffer fmt.Fprintf(&buf, "%d.%d.%d", v.major, v.minor, v.patch) if v.pre != "" { fmt.Fprintf(&buf, "-%s", v.pre) } if v.metadata != "" { fmt.Fprintf(&buf, "+%s", v.metadata) } return buf.String() } // Original returns the original value passed in to be parsed. func (v *Version) Original() string { return v.original } // Major returns the major version. func (v Version) Major() uint64 { return v.major } // Minor returns the minor version. func (v Version) Minor() uint64 { return v.minor } // Patch returns the patch version. func (v Version) Patch() uint64 { return v.patch } // Prerelease returns the pre-release version. func (v Version) Prerelease() string { return v.pre } // Metadata returns the metadata on the version. func (v Version) Metadata() string { return v.metadata } // originalVPrefix returns the original 'v' prefix if any. func (v Version) originalVPrefix() string { // Note, only lowercase v is supported as a prefix by the parser. if v.original != "" && v.original[:1] == "v" { return v.original[:1] } return "" } // IncPatch produces the next patch version. // If the current version does not have prerelease/metadata information, // it unsets metadata and prerelease values, increments patch number. // If the current version has any of prerelease or metadata information, // it unsets both values and keeps current patch value func (v Version) IncPatch() Version { vNext := v // according to http://semver.org/#spec-item-9 // Pre-release versions have a lower precedence than the associated normal version. // according to http://semver.org/#spec-item-10 // Build metadata SHOULD be ignored when determining version precedence. if v.pre != "" { vNext.metadata = "" vNext.pre = "" } else { vNext.metadata = "" vNext.pre = "" vNext.patch = v.patch + 1 } vNext.original = v.originalVPrefix() + "" + vNext.String() return vNext } // IncMinor produces the next minor version. // Sets patch to 0. // Increments minor number. // Unsets metadata. // Unsets prerelease status. func (v Version) IncMinor() Version { vNext := v vNext.metadata = "" vNext.pre = "" vNext.patch = 0 vNext.minor = v.minor + 1 vNext.original = v.originalVPrefix() + "" + vNext.String() return vNext } // IncMajor produces the next major version. // Sets patch to 0. // Sets minor to 0. // Increments major number. // Unsets metadata. // Unsets prerelease status. func (v Version) IncMajor() Version { vNext := v vNext.metadata = "" vNext.pre = "" vNext.patch = 0 vNext.minor = 0 vNext.major = v.major + 1 vNext.original = v.originalVPrefix() + "" + vNext.String() return vNext } // SetPrerelease defines the prerelease value. // Value must not include the required 'hyphen' prefix. func (v Version) SetPrerelease(prerelease string) (Version, error) { vNext := v if len(prerelease) > 0 { if err := validatePrerelease(prerelease); err != nil { return vNext, err } } vNext.pre = prerelease vNext.original = v.originalVPrefix() + "" + vNext.String() return vNext, nil } // SetMetadata defines metadata value. // Value must not include the required 'plus' prefix. func (v Version) SetMetadata(metadata string) (Version, error) { vNext := v if len(metadata) > 0 { if err := validateMetadata(metadata); err != nil { return vNext, err } } vNext.metadata = metadata vNext.original = v.originalVPrefix() + "" + vNext.String() return vNext, nil } // LessThan tests if one version is less than another one. func (v *Version) LessThan(o *Version) bool { return v.Compare(o) < 0 } // LessThanEqual tests if one version is less or equal than another one. func (v *Version) LessThanEqual(o *Version) bool { return v.Compare(o) <= 0 } // GreaterThan tests if one version is greater than another one. func (v *Version) GreaterThan(o *Version) bool { return v.Compare(o) > 0 } // GreaterThanEqual tests if one version is greater or equal than another one. func (v *Version) GreaterThanEqual(o *Version) bool { return v.Compare(o) >= 0 } // Equal tests if two versions are equal to each other. // Note, versions can be equal with different metadata since metadata // is not considered part of the comparable version. func (v *Version) Equal(o *Version) bool { if v == o { return true } if v == nil || o == nil { return false } return v.Compare(o) == 0 } // Compare compares this version to another one. It returns -1, 0, or 1 if // the version smaller, equal, or larger than the other version. // // Versions are compared by X.Y.Z. Build metadata is ignored. Prerelease is // lower than the version without a prerelease. Compare always takes into account // prereleases. If you want to work with ranges using typical range syntaxes that // skip prereleases if the range is not looking for them use constraints. func (v *Version) Compare(o *Version) int { // Compare the major, minor, and patch version for differences. If a // difference is found return the comparison. if d := compareSegment(v.Major(), o.Major()); d != 0 { return d } if d := compareSegment(v.Minor(), o.Minor()); d != 0 { return d } if d := compareSegment(v.Patch(), o.Patch()); d != 0 { return d } // At this point the major, minor, and patch versions are the same. ps := v.pre po := o.Prerelease() if ps == "" && po == "" { return 0 } if ps == "" { return 1 } if po == "" { return -1 } return comparePrerelease(ps, po) } // UnmarshalJSON implements JSON.Unmarshaler interface. func (v *Version) UnmarshalJSON(b []byte) error { var s string if err := json.Unmarshal(b, &s); err != nil { return err } temp, err := NewVersion(s) if err != nil { return err } v.major = temp.major v.minor = temp.minor v.patch = temp.patch v.pre = temp.pre v.metadata = temp.metadata v.original = temp.original return nil } // MarshalJSON implements JSON.Marshaler interface. func (v Version) MarshalJSON() ([]byte, error) { return json.Marshal(v.String()) } // UnmarshalText implements the encoding.TextUnmarshaler interface. func (v *Version) UnmarshalText(text []byte) error { temp, err := NewVersion(string(text)) if err != nil { return err } *v = *temp return nil } // MarshalText implements the encoding.TextMarshaler interface. func (v Version) MarshalText() ([]byte, error) { return []byte(v.String()), nil } // Scan implements the SQL.Scanner interface. func (v *Version) Scan(value interface{}) error { var s string s, _ = value.(string) temp, err := NewVersion(s) if err != nil { return err } v.major = temp.major v.minor = temp.minor v.patch = temp.patch v.pre = temp.pre v.metadata = temp.metadata v.original = temp.original return nil } // Value implements the Driver.Valuer interface. func (v Version) Value() (driver.Value, error) { return v.String(), nil } func compareSegment(v, o uint64) int { if v < o { return -1 } if v > o { return 1 } return 0 } func comparePrerelease(v, o string) int { // split the prelease versions by their part. The separator, per the spec, // is a . sparts := strings.Split(v, ".") oparts := strings.Split(o, ".") // Find the longer length of the parts to know how many loop iterations to // go through. slen := len(sparts) olen := len(oparts) l := slen if olen > slen { l = olen } // Iterate over each part of the prereleases to compare the differences. for i := 0; i < l; i++ { // Since the lentgh of the parts can be different we need to create // a placeholder. This is to avoid out of bounds issues. stemp := "" if i < slen { stemp = sparts[i] } otemp := "" if i < olen { otemp = oparts[i] } d := comparePrePart(stemp, otemp) if d != 0 { return d } } // Reaching here means two versions are of equal value but have different // metadata (the part following a +). They are not identical in string form // but the version comparison finds them to be equal. return 0 } func comparePrePart(s, o string) int { // Fastpath if they are equal if s == o { return 0 } // When s or o are empty we can use the other in an attempt to determine // the response. if s == "" { if o != "" { return -1 } return 1 } if o == "" { if s != "" { return 1 } return -1 } // When comparing strings "99" is greater than "103". To handle // cases like this we need to detect numbers and compare them. According // to the semver spec, numbers are always positive. If there is a - at the // start like -99 this is to be evaluated as an alphanum. numbers always // have precedence over alphanum. Parsing as Uints because negative numbers // are ignored. oi, n1 := strconv.ParseUint(o, 10, 64) si, n2 := strconv.ParseUint(s, 10, 64) // The case where both are strings compare the strings if n1 != nil && n2 != nil { if s > o { return 1 } return -1 } else if n1 != nil { // o is a string and s is a number return -1 } else if n2 != nil { // s is a string and o is a number return 1 } // Both are numbers if si > oi { return 1 } return -1 } // Like strings.ContainsAny but does an only instead of any. func containsOnly(s string, comp string) bool { return strings.IndexFunc(s, func(r rune) bool { return !strings.ContainsRune(comp, r) }) == -1 } // From the spec, "Identifiers MUST comprise only // ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. // Numeric identifiers MUST NOT include leading zeroes.". These segments can // be dot separated. func validatePrerelease(p string) error { eparts := strings.Split(p, ".") for _, p := range eparts { if containsOnly(p, num) { if len(p) > 1 && p[0] == '0' { return ErrSegmentStartsZero } } else if !containsOnly(p, allowed) { return ErrInvalidPrerelease } } return nil } // From the spec, "Build metadata MAY be denoted by // appending a plus sign and a series of dot separated identifiers immediately // following the patch or pre-release version. Identifiers MUST comprise only // ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty." func validateMetadata(m string) error { eparts := strings.Split(m, ".") for _, p := range eparts { if !containsOnly(p, allowed) { return ErrInvalidMetadata } } return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/Masterminds/semver/v3/doc.go
vendor/github.com/Masterminds/semver/v3/doc.go
/* Package semver provides the ability to work with Semantic Versions (http://semver.org) in Go. Specifically it provides the ability to: - Parse semantic versions - Sort semantic versions - Check if a semantic version fits within a set of constraints - Optionally work with a `v` prefix # Parsing Semantic Versions There are two functions that can parse semantic versions. The `StrictNewVersion` function only parses valid version 2 semantic versions as outlined in the specification. The `NewVersion` function attempts to coerce a version into a semantic version and parse it. For example, if there is a leading v or a version listed without all 3 parts (e.g. 1.2) it will attempt to coerce it into a valid semantic version (e.g., 1.2.0). In both cases a `Version` object is returned that can be sorted, compared, and used in constraints. When parsing a version an optional error can be returned if there is an issue parsing the version. For example, v, err := semver.NewVersion("1.2.3-beta.1+b345") The version object has methods to get the parts of the version, compare it to other versions, convert the version back into a string, and get the original string. For more details please see the documentation at https://godoc.org/github.com/Masterminds/semver. # Sorting Semantic Versions A set of versions can be sorted using the `sort` package from the standard library. For example, raw := []string{"1.2.3", "1.0", "1.3", "2", "0.4.2",} vs := make([]*semver.Version, len(raw)) for i, r := range raw { v, err := semver.NewVersion(r) if err != nil { t.Errorf("Error parsing version: %s", err) } vs[i] = v } sort.Sort(semver.Collection(vs)) # Checking Version Constraints and Comparing Versions There are two methods for comparing versions. One uses comparison methods on `Version` instances and the other is using Constraints. There are some important differences to notes between these two methods of comparison. 1. When two versions are compared using functions such as `Compare`, `LessThan`, and others it will follow the specification and always include prereleases within the comparison. It will provide an answer valid with the comparison spec section at https://semver.org/#spec-item-11 2. When constraint checking is used for checks or validation it will follow a different set of rules that are common for ranges with tools like npm/js and Rust/Cargo. This includes considering prereleases to be invalid if the ranges does not include on. If you want to have it include pre-releases a simple solution is to include `-0` in your range. 3. Constraint ranges can have some complex rules including the shorthard use of ~ and ^. For more details on those see the options below. There are differences between the two methods or checking versions because the comparison methods on `Version` follow the specification while comparison ranges are not part of the specification. Different packages and tools have taken it upon themselves to come up with range rules. This has resulted in differences. For example, npm/js and Cargo/Rust follow similar patterns which PHP has a different pattern for ^. The comparison features in this package follow the npm/js and Cargo/Rust lead because applications using it have followed similar patters with their versions. Checking a version against version constraints is one of the most featureful parts of the package. c, err := semver.NewConstraint(">= 1.2.3") if err != nil { // Handle constraint not being parsable. } v, err := semver.NewVersion("1.3") if err != nil { // Handle version not being parsable. } // Check if the version meets the constraints. The a variable will be true. a := c.Check(v) # Basic Comparisons There are two elements to the comparisons. First, a comparison string is a list of comma or space separated AND comparisons. These are then separated by || (OR) comparisons. For example, `">= 1.2 < 3.0.0 || >= 4.2.3"` is looking for a comparison that's greater than or equal to 1.2 and less than 3.0.0 or is greater than or equal to 4.2.3. This can also be written as `">= 1.2, < 3.0.0 || >= 4.2.3"` The basic comparisons are: - `=`: equal (aliased to no operator) - `!=`: not equal - `>`: greater than - `<`: less than - `>=`: greater than or equal to - `<=`: less than or equal to # Hyphen Range Comparisons There are multiple methods to handle ranges and the first is hyphens ranges. These look like: - `1.2 - 1.4.5` which is equivalent to `>= 1.2, <= 1.4.5` - `2.3.4 - 4.5` which is equivalent to `>= 2.3.4 <= 4.5` # Wildcards In Comparisons The `x`, `X`, and `*` characters can be used as a wildcard character. This works for all comparison operators. When used on the `=` operator it falls back to the tilde operation. For example, - `1.2.x` is equivalent to `>= 1.2.0 < 1.3.0` - `>= 1.2.x` is equivalent to `>= 1.2.0` - `<= 2.x` is equivalent to `<= 3` - `*` is equivalent to `>= 0.0.0` Tilde Range Comparisons (Patch) The tilde (`~`) comparison operator is for patch level ranges when a minor version is specified and major level changes when the minor number is missing. For example, - `~1.2.3` is equivalent to `>= 1.2.3 < 1.3.0` - `~1` is equivalent to `>= 1, < 2` - `~2.3` is equivalent to `>= 2.3 < 2.4` - `~1.2.x` is equivalent to `>= 1.2.0 < 1.3.0` - `~1.x` is equivalent to `>= 1 < 2` Caret Range Comparisons (Major) The caret (`^`) comparison operator is for major level changes once a stable (1.0.0) release has occurred. Prior to a 1.0.0 release the minor versions acts as the API stability level. This is useful when comparisons of API versions as a major change is API breaking. For example, - `^1.2.3` is equivalent to `>= 1.2.3, < 2.0.0` - `^1.2.x` is equivalent to `>= 1.2.0, < 2.0.0` - `^2.3` is equivalent to `>= 2.3, < 3` - `^2.x` is equivalent to `>= 2.0.0, < 3` - `^0.2.3` is equivalent to `>=0.2.3 <0.3.0` - `^0.2` is equivalent to `>=0.2.0 <0.3.0` - `^0.0.3` is equivalent to `>=0.0.3 <0.0.4` - `^0.0` is equivalent to `>=0.0.0 <0.1.0` - `^0` is equivalent to `>=0.0.0 <1.0.0` # Validation In addition to testing a version against a constraint, a version can be validated against a constraint. When validation fails a slice of errors containing why a version didn't meet the constraint is returned. For example, c, err := semver.NewConstraint("<= 1.2.3, >= 1.4") if err != nil { // Handle constraint not being parseable. } v, _ := semver.NewVersion("1.3") if err != nil { // Handle version not being parseable. } // Validate a version against a constraint. a, msgs := c.Validate(v) // a is false for _, m := range msgs { fmt.Println(m) // Loops over the errors which would read // "1.3 is greater than 1.2.3" // "1.3 is less than 1.4" } */ package semver
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/evanphx/json-patch/v5/merge.go
vendor/github.com/evanphx/json-patch/v5/merge.go
package jsonpatch import ( "bytes" "errors" "fmt" "io" "reflect" "github.com/evanphx/json-patch/v5/internal/json" ) func merge(cur, patch *lazyNode, mergeMerge bool, options *ApplyOptions) *lazyNode { curDoc, err := cur.intoDoc(options) if err != nil { pruneNulls(patch, options) return patch } patchDoc, err := patch.intoDoc(options) if err != nil { return patch } mergeDocs(curDoc, patchDoc, mergeMerge, options) return cur } func mergeDocs(doc, patch *partialDoc, mergeMerge bool, options *ApplyOptions) { for k, v := range patch.obj { if v == nil { if mergeMerge { idx := -1 for i, key := range doc.keys { if key == k { idx = i break } } if idx == -1 { doc.keys = append(doc.keys, k) } doc.obj[k] = nil } else { _ = doc.remove(k, options) } } else { cur, ok := doc.obj[k] if !ok || cur == nil { if !mergeMerge { pruneNulls(v, options) } _ = doc.set(k, v, options) } else { _ = doc.set(k, merge(cur, v, mergeMerge, options), options) } } } } func pruneNulls(n *lazyNode, options *ApplyOptions) { sub, err := n.intoDoc(options) if err == nil { pruneDocNulls(sub, options) } else { ary, err := n.intoAry() if err == nil { pruneAryNulls(ary, options) } } } func pruneDocNulls(doc *partialDoc, options *ApplyOptions) *partialDoc { for k, v := range doc.obj { if v == nil { _ = doc.remove(k, &ApplyOptions{}) } else { pruneNulls(v, options) } } return doc } func pruneAryNulls(ary *partialArray, options *ApplyOptions) *partialArray { newAry := []*lazyNode{} for _, v := range ary.nodes { if v != nil { pruneNulls(v, options) } newAry = append(newAry, v) } ary.nodes = newAry return ary } var ErrBadJSONDoc = fmt.Errorf("Invalid JSON Document") var ErrBadJSONPatch = fmt.Errorf("Invalid JSON Patch") var errBadMergeTypes = fmt.Errorf("Mismatched JSON Documents") // MergeMergePatches merges two merge patches together, such that // applying this resulting merged merge patch to a document yields the same // as merging each merge patch to the document in succession. func MergeMergePatches(patch1Data, patch2Data []byte) ([]byte, error) { return doMergePatch(patch1Data, patch2Data, true) } // MergePatch merges the patchData into the docData. func MergePatch(docData, patchData []byte) ([]byte, error) { return doMergePatch(docData, patchData, false) } func doMergePatch(docData, patchData []byte, mergeMerge bool) ([]byte, error) { if !json.Valid(docData) { return nil, ErrBadJSONDoc } if !json.Valid(patchData) { return nil, ErrBadJSONPatch } options := NewApplyOptions() doc := &partialDoc{ opts: options, } docErr := doc.UnmarshalJSON(docData) patch := &partialDoc{ opts: options, } patchErr := patch.UnmarshalJSON(patchData) if isSyntaxError(docErr) { return nil, ErrBadJSONDoc } if isSyntaxError(patchErr) { return patchData, nil } if docErr == nil && doc.obj == nil { return nil, ErrBadJSONDoc } if patchErr == nil && patch.obj == nil { return patchData, nil } if docErr != nil || patchErr != nil { // Not an error, just not a doc, so we turn straight into the patch if patchErr == nil { if mergeMerge { doc = patch } else { doc = pruneDocNulls(patch, options) } } else { patchAry := &partialArray{} patchErr = unmarshal(patchData, &patchAry.nodes) if patchErr != nil { // Not an array either, a literal is the result directly. if json.Valid(patchData) { return patchData, nil } return nil, ErrBadJSONPatch } pruneAryNulls(patchAry, options) out, patchErr := json.Marshal(patchAry.nodes) if patchErr != nil { return nil, ErrBadJSONPatch } return out, nil } } else { mergeDocs(doc, patch, mergeMerge, options) } return json.Marshal(doc) } func isSyntaxError(err error) bool { if errors.Is(err, io.EOF) { return true } if errors.Is(err, io.ErrUnexpectedEOF) { return true } if _, ok := err.(*json.SyntaxError); ok { return true } if _, ok := err.(*syntaxError); ok { return true } return false } // resemblesJSONArray indicates whether the byte-slice "appears" to be // a JSON array or not. // False-positives are possible, as this function does not check the internal // structure of the array. It only checks that the outer syntax is present and // correct. func resemblesJSONArray(input []byte) bool { input = bytes.TrimSpace(input) hasPrefix := bytes.HasPrefix(input, []byte("[")) hasSuffix := bytes.HasSuffix(input, []byte("]")) return hasPrefix && hasSuffix } // CreateMergePatch will return a merge patch document capable of converting // the original document(s) to the modified document(s). // The parameters can be bytes of either two JSON Documents, or two arrays of // JSON documents. // The merge patch returned follows the specification defined at http://tools.ietf.org/html/draft-ietf-appsawg-json-merge-patch-07 func CreateMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) { originalResemblesArray := resemblesJSONArray(originalJSON) modifiedResemblesArray := resemblesJSONArray(modifiedJSON) // Do both byte-slices seem like JSON arrays? if originalResemblesArray && modifiedResemblesArray { return createArrayMergePatch(originalJSON, modifiedJSON) } // Are both byte-slices are not arrays? Then they are likely JSON objects... if !originalResemblesArray && !modifiedResemblesArray { return createObjectMergePatch(originalJSON, modifiedJSON) } // None of the above? Then return an error because of mismatched types. return nil, errBadMergeTypes } // createObjectMergePatch will return a merge-patch document capable of // converting the original document to the modified document. func createObjectMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) { originalDoc := map[string]interface{}{} modifiedDoc := map[string]interface{}{} err := unmarshal(originalJSON, &originalDoc) if err != nil { return nil, ErrBadJSONDoc } err = unmarshal(modifiedJSON, &modifiedDoc) if err != nil { return nil, ErrBadJSONDoc } dest, err := getDiff(originalDoc, modifiedDoc) if err != nil { return nil, err } return json.Marshal(dest) } func unmarshal(data []byte, into interface{}) error { return json.UnmarshalValid(data, into) } // createArrayMergePatch will return an array of merge-patch documents capable // of converting the original document to the modified document for each // pair of JSON documents provided in the arrays. // Arrays of mismatched sizes will result in an error. func createArrayMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) { originalDocs := []json.RawMessage{} modifiedDocs := []json.RawMessage{} err := unmarshal(originalJSON, &originalDocs) if err != nil { return nil, ErrBadJSONDoc } err = unmarshal(modifiedJSON, &modifiedDocs) if err != nil { return nil, ErrBadJSONDoc } total := len(originalDocs) if len(modifiedDocs) != total { return nil, ErrBadJSONDoc } result := []json.RawMessage{} for i := 0; i < len(originalDocs); i++ { original := originalDocs[i] modified := modifiedDocs[i] patch, err := createObjectMergePatch(original, modified) if err != nil { return nil, err } result = append(result, json.RawMessage(patch)) } return json.Marshal(result) } // Returns true if the array matches (must be json types). // As is idiomatic for go, an empty array is not the same as a nil array. func matchesArray(a, b []interface{}) bool { if len(a) != len(b) { return false } if (a == nil && b != nil) || (a != nil && b == nil) { return false } for i := range a { if !matchesValue(a[i], b[i]) { return false } } return true } // Returns true if the values matches (must be json types) // The types of the values must match, otherwise it will always return false // If two map[string]interface{} are given, all elements must match. func matchesValue(av, bv interface{}) bool { if reflect.TypeOf(av) != reflect.TypeOf(bv) { return false } switch at := av.(type) { case string: bt := bv.(string) if bt == at { return true } case json.Number: bt := bv.(json.Number) if bt == at { return true } case float64: bt := bv.(float64) if bt == at { return true } case bool: bt := bv.(bool) if bt == at { return true } case nil: // Both nil, fine. return true case map[string]interface{}: bt := bv.(map[string]interface{}) if len(bt) != len(at) { return false } for key := range bt { av, aOK := at[key] bv, bOK := bt[key] if aOK != bOK { return false } if !matchesValue(av, bv) { return false } } return true case []interface{}: bt := bv.([]interface{}) return matchesArray(at, bt) } return false } // getDiff returns the (recursive) difference between a and b as a map[string]interface{}. func getDiff(a, b map[string]interface{}) (map[string]interface{}, error) { into := map[string]interface{}{} for key, bv := range b { av, ok := a[key] // value was added if !ok { into[key] = bv continue } // If types have changed, replace completely if reflect.TypeOf(av) != reflect.TypeOf(bv) { into[key] = bv continue } // Types are the same, compare values switch at := av.(type) { case map[string]interface{}: bt := bv.(map[string]interface{}) dst := make(map[string]interface{}, len(bt)) dst, err := getDiff(at, bt) if err != nil { return nil, err } if len(dst) > 0 { into[key] = dst } case string, float64, bool, json.Number: if !matchesValue(av, bv) { into[key] = bv } case []interface{}: bt := bv.([]interface{}) if !matchesArray(at, bt) { into[key] = bv } case nil: switch bv.(type) { case nil: // Both nil, fine. default: into[key] = bv } default: panic(fmt.Sprintf("Unknown type:%T in key %s", av, key)) } } // Now add all deleted values as nil for key := range a { _, found := b[key] if !found { into[key] = nil } } return into, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/evanphx/json-patch/v5/errors.go
vendor/github.com/evanphx/json-patch/v5/errors.go
package jsonpatch import "fmt" // AccumulatedCopySizeError is an error type returned when the accumulated size // increase caused by copy operations in a patch operation has exceeded the // limit. type AccumulatedCopySizeError struct { limit int64 accumulated int64 } // NewAccumulatedCopySizeError returns an AccumulatedCopySizeError. func NewAccumulatedCopySizeError(l, a int64) *AccumulatedCopySizeError { return &AccumulatedCopySizeError{limit: l, accumulated: a} } // Error implements the error interface. func (a *AccumulatedCopySizeError) Error() string { return fmt.Sprintf("Unable to complete the copy, the accumulated size increase of copy is %d, exceeding the limit %d", a.accumulated, a.limit) } // ArraySizeError is an error type returned when the array size has exceeded // the limit. type ArraySizeError struct { limit int size int } // NewArraySizeError returns an ArraySizeError. func NewArraySizeError(l, s int) *ArraySizeError { return &ArraySizeError{limit: l, size: s} } // Error implements the error interface. func (a *ArraySizeError) Error() string { return fmt.Sprintf("Unable to create array of size %d, limit is %d", a.size, a.limit) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/evanphx/json-patch/v5/patch.go
vendor/github.com/evanphx/json-patch/v5/patch.go
package jsonpatch import ( "bytes" "errors" "fmt" "strconv" "strings" "unicode" "github.com/evanphx/json-patch/v5/internal/json" ) const ( eRaw = iota eDoc eAry ) var ( // SupportNegativeIndices decides whether to support non-standard practice of // allowing negative indices to mean indices starting at the end of an array. // Default to true. SupportNegativeIndices bool = true // AccumulatedCopySizeLimit limits the total size increase in bytes caused by // "copy" operations in a patch. AccumulatedCopySizeLimit int64 = 0 startObject = json.Delim('{') endObject = json.Delim('}') startArray = json.Delim('[') endArray = json.Delim(']') ) var ( ErrTestFailed = errors.New("test failed") ErrMissing = errors.New("missing value") ErrUnknownType = errors.New("unknown object type") ErrInvalid = errors.New("invalid state detected") ErrInvalidIndex = errors.New("invalid index referenced") ErrExpectedObject = errors.New("invalid value, expected object") rawJSONArray = []byte("[]") rawJSONObject = []byte("{}") rawJSONNull = []byte("null") ) type lazyNode struct { raw *json.RawMessage doc *partialDoc ary *partialArray which int } // Operation is a single JSON-Patch step, such as a single 'add' operation. type Operation map[string]*json.RawMessage // Patch is an ordered collection of Operations. type Patch []Operation type partialDoc struct { self *lazyNode keys []string obj map[string]*lazyNode opts *ApplyOptions } type partialArray struct { self *lazyNode nodes []*lazyNode } type container interface { get(key string, options *ApplyOptions) (*lazyNode, error) set(key string, val *lazyNode, options *ApplyOptions) error add(key string, val *lazyNode, options *ApplyOptions) error remove(key string, options *ApplyOptions) error } // ApplyOptions specifies options for calls to ApplyWithOptions. // Use NewApplyOptions to obtain default values for ApplyOptions. type ApplyOptions struct { // SupportNegativeIndices decides whether to support non-standard practice of // allowing negative indices to mean indices starting at the end of an array. // Default to true. SupportNegativeIndices bool // AccumulatedCopySizeLimit limits the total size increase in bytes caused by // "copy" operations in a patch. AccumulatedCopySizeLimit int64 // AllowMissingPathOnRemove indicates whether to fail "remove" operations when the target path is missing. // Default to false. AllowMissingPathOnRemove bool // EnsurePathExistsOnAdd instructs json-patch to recursively create the missing parts of path on "add" operation. // Default to false. EnsurePathExistsOnAdd bool EscapeHTML bool } // NewApplyOptions creates a default set of options for calls to ApplyWithOptions. func NewApplyOptions() *ApplyOptions { return &ApplyOptions{ SupportNegativeIndices: SupportNegativeIndices, AccumulatedCopySizeLimit: AccumulatedCopySizeLimit, AllowMissingPathOnRemove: false, EnsurePathExistsOnAdd: false, EscapeHTML: true, } } func newLazyNode(raw *json.RawMessage) *lazyNode { return &lazyNode{raw: raw, doc: nil, ary: nil, which: eRaw} } func newRawMessage(buf []byte) *json.RawMessage { ra := make(json.RawMessage, len(buf)) copy(ra, buf) return &ra } func (n *lazyNode) RedirectMarshalJSON() (any, error) { switch n.which { case eRaw: return n.raw, nil case eDoc: return n.doc, nil case eAry: return n.ary.nodes, nil default: return nil, ErrUnknownType } } func (n *lazyNode) UnmarshalJSON(data []byte) error { dest := make(json.RawMessage, len(data)) copy(dest, data) n.raw = &dest n.which = eRaw return nil } func (n *partialDoc) TrustMarshalJSON(buf *bytes.Buffer) error { if n.obj == nil { return ErrExpectedObject } if err := buf.WriteByte('{'); err != nil { return err } escaped := true // n.opts should always be set, but in case we missed a case, // guard. if n.opts != nil { escaped = n.opts.EscapeHTML } for i, k := range n.keys { if i > 0 { if err := buf.WriteByte(','); err != nil { return err } } key, err := json.MarshalEscaped(k, escaped) if err != nil { return err } if _, err := buf.Write(key); err != nil { return err } if err := buf.WriteByte(':'); err != nil { return err } value, err := json.MarshalEscaped(n.obj[k], escaped) if err != nil { return err } if _, err := buf.Write(value); err != nil { return err } } if err := buf.WriteByte('}'); err != nil { return err } return nil } type syntaxError struct { msg string } func (err *syntaxError) Error() string { return err.msg } func (n *partialDoc) UnmarshalJSON(data []byte) error { keys, err := json.UnmarshalValidWithKeys(data, &n.obj) if err != nil { return err } n.keys = keys return nil } func (n *partialArray) UnmarshalJSON(data []byte) error { return json.UnmarshalValid(data, &n.nodes) } func (n *partialArray) RedirectMarshalJSON() (interface{}, error) { return n.nodes, nil } func deepCopy(src *lazyNode, options *ApplyOptions) (*lazyNode, int, error) { if src == nil { return nil, 0, nil } a, err := json.MarshalEscaped(src, options.EscapeHTML) if err != nil { return nil, 0, err } sz := len(a) return newLazyNode(newRawMessage(a)), sz, nil } func (n *lazyNode) nextByte() byte { s := []byte(*n.raw) for unicode.IsSpace(rune(s[0])) { s = s[1:] } return s[0] } func (n *lazyNode) intoDoc(options *ApplyOptions) (*partialDoc, error) { if n.which == eDoc { return n.doc, nil } if n.raw == nil { return nil, ErrInvalid } if n.nextByte() != '{' { return nil, ErrInvalid } err := unmarshal(*n.raw, &n.doc) if n.doc == nil { return nil, ErrInvalid } n.doc.opts = options if err != nil { return nil, err } n.which = eDoc return n.doc, nil } func (n *lazyNode) intoAry() (*partialArray, error) { if n.which == eAry { return n.ary, nil } if n.raw == nil { return nil, ErrInvalid } err := unmarshal(*n.raw, &n.ary) if err != nil { return nil, err } n.which = eAry return n.ary, nil } func (n *lazyNode) compact() []byte { buf := &bytes.Buffer{} if n.raw == nil { return nil } err := json.Compact(buf, *n.raw) if err != nil { return *n.raw } return buf.Bytes() } func (n *lazyNode) tryDoc() bool { if n.raw == nil { return false } err := unmarshal(*n.raw, &n.doc) if err != nil { return false } if n.doc == nil { return false } n.which = eDoc return true } func (n *lazyNode) tryAry() bool { if n.raw == nil { return false } err := unmarshal(*n.raw, &n.ary) if err != nil { return false } n.which = eAry return true } func (n *lazyNode) isNull() bool { if n == nil { return true } if n.raw == nil { return true } return bytes.Equal(n.compact(), rawJSONNull) } func (n *lazyNode) equal(o *lazyNode) bool { if n.which == eRaw { if !n.tryDoc() && !n.tryAry() { if o.which != eRaw { return false } nc := n.compact() oc := o.compact() if nc[0] == '"' && oc[0] == '"' { // ok, 2 strings var ns, os string err := json.UnmarshalValid(nc, &ns) if err != nil { return false } err = json.UnmarshalValid(oc, &os) if err != nil { return false } return ns == os } return bytes.Equal(nc, oc) } } if n.which == eDoc { if o.which == eRaw { if !o.tryDoc() { return false } } if o.which != eDoc { return false } if len(n.doc.obj) != len(o.doc.obj) { return false } for k, v := range n.doc.obj { ov, ok := o.doc.obj[k] if !ok { return false } if (v == nil) != (ov == nil) { return false } if v == nil && ov == nil { continue } if !v.equal(ov) { return false } } return true } if o.which != eAry && !o.tryAry() { return false } if len(n.ary.nodes) != len(o.ary.nodes) { return false } for idx, val := range n.ary.nodes { if !val.equal(o.ary.nodes[idx]) { return false } } return true } // Kind reads the "op" field of the Operation. func (o Operation) Kind() string { if obj, ok := o["op"]; ok && obj != nil { var op string err := unmarshal(*obj, &op) if err != nil { return "unknown" } return op } return "unknown" } // Path reads the "path" field of the Operation. func (o Operation) Path() (string, error) { if obj, ok := o["path"]; ok && obj != nil { var op string err := unmarshal(*obj, &op) if err != nil { return "unknown", err } return op, nil } return "unknown", fmt.Errorf("operation missing path field: %w", ErrMissing) } // From reads the "from" field of the Operation. func (o Operation) From() (string, error) { if obj, ok := o["from"]; ok && obj != nil { var op string err := unmarshal(*obj, &op) if err != nil { return "unknown", err } return op, nil } return "unknown", fmt.Errorf("operation, missing from field: %w", ErrMissing) } func (o Operation) value() *lazyNode { if obj, ok := o["value"]; ok { // A `null` gets decoded as a nil RawMessage, so let's fix it up here. if obj == nil { return newLazyNode(newRawMessage(rawJSONNull)) } return newLazyNode(obj) } return nil } // ValueInterface decodes the operation value into an interface. func (o Operation) ValueInterface() (interface{}, error) { if obj, ok := o["value"]; ok { if obj == nil { return nil, nil } var v interface{} err := unmarshal(*obj, &v) if err != nil { return nil, err } return v, nil } return nil, fmt.Errorf("operation, missing value field: %w", ErrMissing) } func isArray(buf []byte) bool { Loop: for _, c := range buf { switch c { case ' ': case '\n': case '\t': continue case '[': return true default: break Loop } } return false } func findObject(pd *container, path string, options *ApplyOptions) (container, string) { doc := *pd split := strings.Split(path, "/") if len(split) < 2 { if path == "" { return doc, "" } return nil, "" } parts := split[1 : len(split)-1] key := split[len(split)-1] var err error for _, part := range parts { next, ok := doc.get(decodePatchKey(part), options) if next == nil || ok != nil { return nil, "" } if isArray(*next.raw) { doc, err = next.intoAry() if err != nil { return nil, "" } } else { doc, err = next.intoDoc(options) if err != nil { return nil, "" } } } return doc, decodePatchKey(key) } func (d *partialDoc) set(key string, val *lazyNode, options *ApplyOptions) error { if d.obj == nil { return ErrExpectedObject } found := false for _, k := range d.keys { if k == key { found = true break } } if !found { d.keys = append(d.keys, key) } d.obj[key] = val return nil } func (d *partialDoc) add(key string, val *lazyNode, options *ApplyOptions) error { return d.set(key, val, options) } func (d *partialDoc) get(key string, options *ApplyOptions) (*lazyNode, error) { if key == "" { return d.self, nil } if d.obj == nil { return nil, ErrExpectedObject } v, ok := d.obj[key] if !ok { return v, fmt.Errorf("unable to get nonexistent key: %s: %w", key, ErrMissing) } return v, nil } func (d *partialDoc) remove(key string, options *ApplyOptions) error { if d.obj == nil { return ErrExpectedObject } _, ok := d.obj[key] if !ok { if options.AllowMissingPathOnRemove { return nil } return fmt.Errorf("unable to remove nonexistent key: %s: %w", key, ErrMissing) } idx := -1 for i, k := range d.keys { if k == key { idx = i break } } d.keys = append(d.keys[0:idx], d.keys[idx+1:]...) delete(d.obj, key) return nil } // set should only be used to implement the "replace" operation, so "key" must // be an already existing index in "d". func (d *partialArray) set(key string, val *lazyNode, options *ApplyOptions) error { idx, err := strconv.Atoi(key) if err != nil { return err } if idx < 0 { if !options.SupportNegativeIndices { return fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } if idx < -len(d.nodes) { return fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } idx += len(d.nodes) } d.nodes[idx] = val return nil } func (d *partialArray) add(key string, val *lazyNode, options *ApplyOptions) error { if key == "-" { d.nodes = append(d.nodes, val) return nil } idx, err := strconv.Atoi(key) if err != nil { return fmt.Errorf("value was not a proper array index: '%s': %w", key, err) } sz := len(d.nodes) + 1 ary := make([]*lazyNode, sz) cur := d if idx >= len(ary) { return fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } if idx < 0 { if !options.SupportNegativeIndices { return fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } if idx < -len(ary) { return fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } idx += len(ary) } copy(ary[0:idx], cur.nodes[0:idx]) ary[idx] = val copy(ary[idx+1:], cur.nodes[idx:]) d.nodes = ary return nil } func (d *partialArray) get(key string, options *ApplyOptions) (*lazyNode, error) { if key == "" { return d.self, nil } idx, err := strconv.Atoi(key) if err != nil { return nil, err } if idx < 0 { if !options.SupportNegativeIndices { return nil, fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } if idx < -len(d.nodes) { return nil, fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } idx += len(d.nodes) } if idx >= len(d.nodes) { return nil, fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } return d.nodes[idx], nil } func (d *partialArray) remove(key string, options *ApplyOptions) error { idx, err := strconv.Atoi(key) if err != nil { return err } cur := d if idx >= len(cur.nodes) { if options.AllowMissingPathOnRemove { return nil } return fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } if idx < 0 { if !options.SupportNegativeIndices { return fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } if idx < -len(cur.nodes) { if options.AllowMissingPathOnRemove { return nil } return fmt.Errorf("Unable to access invalid index: %d: %w", idx, ErrInvalidIndex) } idx += len(cur.nodes) } ary := make([]*lazyNode, len(cur.nodes)-1) copy(ary[0:idx], cur.nodes[0:idx]) copy(ary[idx:], cur.nodes[idx+1:]) d.nodes = ary return nil } func (p Patch) add(doc *container, op Operation, options *ApplyOptions) error { path, err := op.Path() if err != nil { return fmt.Errorf("add operation failed to decode path: %w", ErrMissing) } // special case, adding to empty means replacing the container with the value given if path == "" { val := op.value() var pd container if (*val.raw)[0] == '[' { pd = &partialArray{ self: val, } } else { pd = &partialDoc{ self: val, opts: options, } } err := json.UnmarshalValid(*val.raw, pd) if err != nil { return err } *doc = pd return nil } if options.EnsurePathExistsOnAdd { err = ensurePathExists(doc, path, options) if err != nil { return err } } con, key := findObject(doc, path, options) if con == nil { return fmt.Errorf("add operation does not apply: doc is missing path: \"%s\": %w", path, ErrMissing) } err = con.add(key, op.value(), options) if err != nil { return fmt.Errorf("error in add for path: '%s': %w", path, err) } return nil } // Given a document and a path to a key, walk the path and create all missing elements // creating objects and arrays as needed. func ensurePathExists(pd *container, path string, options *ApplyOptions) error { doc := *pd var err error var arrIndex int split := strings.Split(path, "/") if len(split) < 2 { return nil } parts := split[1:] for pi, part := range parts { // Have we reached the key part of the path? // If yes, we're done. if pi == len(parts)-1 { return nil } target, ok := doc.get(decodePatchKey(part), options) if target == nil || ok != nil { // If the current container is an array which has fewer elements than our target index, // pad the current container with nulls. if arrIndex, err = strconv.Atoi(part); err == nil { pa, ok := doc.(*partialArray) if ok && arrIndex >= len(pa.nodes)+1 { // Pad the array with null values up to the required index. for i := len(pa.nodes); i <= arrIndex-1; i++ { doc.add(strconv.Itoa(i), newLazyNode(newRawMessage(rawJSONNull)), options) } } } // Check if the next part is a numeric index or "-". // If yes, then create an array, otherwise, create an object. if arrIndex, err = strconv.Atoi(parts[pi+1]); err == nil || parts[pi+1] == "-" { if arrIndex < 0 { if !options.SupportNegativeIndices { return fmt.Errorf("Unable to ensure path for invalid index: %d: %w", arrIndex, ErrInvalidIndex) } if arrIndex < -1 { return fmt.Errorf("Unable to ensure path for negative index other than -1: %d: %w", arrIndex, ErrInvalidIndex) } arrIndex = 0 } newNode := newLazyNode(newRawMessage(rawJSONArray)) doc.add(part, newNode, options) doc, _ = newNode.intoAry() // Pad the new array with null values up to the required index. for i := 0; i < arrIndex; i++ { doc.add(strconv.Itoa(i), newLazyNode(newRawMessage(rawJSONNull)), options) } } else { newNode := newLazyNode(newRawMessage(rawJSONObject)) doc.add(part, newNode, options) doc, err = newNode.intoDoc(options) if err != nil { return err } } } else { if isArray(*target.raw) { doc, err = target.intoAry() if err != nil { return err } } else { doc, err = target.intoDoc(options) if err != nil { return err } } } } return nil } func validateOperation(op Operation) error { switch op.Kind() { case "add", "replace": if _, err := op.ValueInterface(); err != nil { return fmt.Errorf("failed to decode 'value': %w", err) } case "move", "copy": if _, err := op.From(); err != nil { return fmt.Errorf("failed to decode 'from': %w", err) } case "remove", "test": default: return fmt.Errorf("unsupported operation") } if _, err := op.Path(); err != nil { return fmt.Errorf("failed to decode 'path': %w", err) } return nil } func validatePatch(p Patch) error { for _, op := range p { if err := validateOperation(op); err != nil { opData, infoErr := json.Marshal(op) if infoErr != nil { return fmt.Errorf("invalid operation: %w", err) } return fmt.Errorf("invalid operation %s: %w", opData, err) } } return nil } func (p Patch) remove(doc *container, op Operation, options *ApplyOptions) error { path, err := op.Path() if err != nil { return fmt.Errorf("remove operation failed to decode path: %w", ErrMissing) } con, key := findObject(doc, path, options) if con == nil { if options.AllowMissingPathOnRemove { return nil } return fmt.Errorf("remove operation does not apply: doc is missing path: \"%s\": %w", path, ErrMissing) } err = con.remove(key, options) if err != nil { return fmt.Errorf("error in remove for path: '%s': %w", path, err) } return nil } func (p Patch) replace(doc *container, op Operation, options *ApplyOptions) error { path, err := op.Path() if err != nil { return fmt.Errorf("replace operation failed to decode path: %w", err) } if path == "" { val := op.value() if val.which == eRaw { if !val.tryDoc() { if !val.tryAry() { return fmt.Errorf("replace operation value must be object or array: %w", err) } } else { val.doc.opts = options } } switch val.which { case eAry: *doc = val.ary case eDoc: *doc = val.doc case eRaw: return fmt.Errorf("replace operation hit impossible case: %w", err) } return nil } con, key := findObject(doc, path, options) if con == nil { return fmt.Errorf("replace operation does not apply: doc is missing path: %s: %w", path, ErrMissing) } _, ok := con.get(key, options) if ok != nil { return fmt.Errorf("replace operation does not apply: doc is missing key: %s: %w", path, ErrMissing) } err = con.set(key, op.value(), options) if err != nil { return fmt.Errorf("error in remove for path: '%s': %w", path, err) } return nil } func (p Patch) move(doc *container, op Operation, options *ApplyOptions) error { from, err := op.From() if err != nil { return fmt.Errorf("move operation failed to decode from: %w", err) } if from == "" { return fmt.Errorf("unable to move entire document to another path: %w", ErrInvalid) } con, key := findObject(doc, from, options) if con == nil { return fmt.Errorf("move operation does not apply: doc is missing from path: %s: %w", from, ErrMissing) } val, err := con.get(key, options) if err != nil { return fmt.Errorf("error in move for path: '%s': %w", key, err) } err = con.remove(key, options) if err != nil { return fmt.Errorf("error in move for path: '%s': %w", key, err) } path, err := op.Path() if err != nil { return fmt.Errorf("move operation failed to decode path: %w", err) } con, key = findObject(doc, path, options) if con == nil { return fmt.Errorf("move operation does not apply: doc is missing destination path: %s: %w", path, ErrMissing) } err = con.add(key, val, options) if err != nil { return fmt.Errorf("error in move for path: '%s': %w", path, err) } return nil } func (p Patch) test(doc *container, op Operation, options *ApplyOptions) error { path, err := op.Path() if err != nil { return fmt.Errorf("test operation failed to decode path: %w", err) } if path == "" { var self lazyNode switch sv := (*doc).(type) { case *partialDoc: self.doc = sv self.which = eDoc case *partialArray: self.ary = sv self.which = eAry } if self.equal(op.value()) { return nil } return fmt.Errorf("testing value %s failed: %w", path, ErrTestFailed) } con, key := findObject(doc, path, options) if con == nil { return fmt.Errorf("test operation does not apply: is missing path: %s: %w", path, ErrMissing) } val, err := con.get(key, options) if err != nil && errors.Unwrap(err) != ErrMissing { return fmt.Errorf("error in test for path: '%s': %w", path, err) } ov := op.value() if val == nil { if ov.isNull() { return nil } return fmt.Errorf("testing value %s failed: %w", path, ErrTestFailed) } else if ov.isNull() { return fmt.Errorf("testing value %s failed: %w", path, ErrTestFailed) } if val.equal(op.value()) { return nil } return fmt.Errorf("testing value %s failed: %w", path, ErrTestFailed) } func (p Patch) copy(doc *container, op Operation, accumulatedCopySize *int64, options *ApplyOptions) error { from, err := op.From() if err != nil { return fmt.Errorf("copy operation failed to decode from: %w", err) } con, key := findObject(doc, from, options) if con == nil { return fmt.Errorf("copy operation does not apply: doc is missing from path: \"%s\": %w", from, ErrMissing) } val, err := con.get(key, options) if err != nil { return fmt.Errorf("error in copy for from: '%s': %w", from, err) } path, err := op.Path() if err != nil { return fmt.Errorf("copy operation failed to decode path: %w", ErrMissing) } con, key = findObject(doc, path, options) if con == nil { return fmt.Errorf("copy operation does not apply: doc is missing destination path: %s: %w", path, ErrMissing) } valCopy, sz, err := deepCopy(val, options) if err != nil { return fmt.Errorf("error while performing deep copy: %w", err) } (*accumulatedCopySize) += int64(sz) if options.AccumulatedCopySizeLimit > 0 && *accumulatedCopySize > options.AccumulatedCopySizeLimit { return NewAccumulatedCopySizeError(options.AccumulatedCopySizeLimit, *accumulatedCopySize) } err = con.add(key, valCopy, options) if err != nil { return fmt.Errorf("error while adding value during copy: %w", err) } return nil } // Equal indicates if 2 JSON documents have the same structural equality. func Equal(a, b []byte) bool { la := newLazyNode(newRawMessage(a)) lb := newLazyNode(newRawMessage(b)) return la.equal(lb) } // DecodePatch decodes the passed JSON document as an RFC 6902 patch. func DecodePatch(buf []byte) (Patch, error) { if !json.Valid(buf) { return nil, ErrInvalid } var p Patch err := unmarshal(buf, &p) if err != nil { return nil, err } if err := validatePatch(p); err != nil { return nil, err } return p, nil } // Apply mutates a JSON document according to the patch, and returns the new // document. func (p Patch) Apply(doc []byte) ([]byte, error) { return p.ApplyWithOptions(doc, NewApplyOptions()) } // ApplyWithOptions mutates a JSON document according to the patch and the passed in ApplyOptions. // It returns the new document. func (p Patch) ApplyWithOptions(doc []byte, options *ApplyOptions) ([]byte, error) { return p.ApplyIndentWithOptions(doc, "", options) } // ApplyIndent mutates a JSON document according to the patch, and returns the new // document indented. func (p Patch) ApplyIndent(doc []byte, indent string) ([]byte, error) { return p.ApplyIndentWithOptions(doc, indent, NewApplyOptions()) } // ApplyIndentWithOptions mutates a JSON document according to the patch and the passed in ApplyOptions. // It returns the new document indented. func (p Patch) ApplyIndentWithOptions(doc []byte, indent string, options *ApplyOptions) ([]byte, error) { if len(doc) == 0 { return doc, nil } if !json.Valid(doc) { return nil, ErrInvalid } raw := json.RawMessage(doc) self := newLazyNode(&raw) var pd container if doc[0] == '[' { pd = &partialArray{ self: self, } } else { pd = &partialDoc{ self: self, opts: options, } } err := unmarshal(doc, pd) if err != nil { return nil, err } err = nil var accumulatedCopySize int64 for _, op := range p { switch op.Kind() { case "add": err = p.add(&pd, op, options) case "remove": err = p.remove(&pd, op, options) case "replace": err = p.replace(&pd, op, options) case "move": err = p.move(&pd, op, options) case "test": err = p.test(&pd, op, options) case "copy": err = p.copy(&pd, op, &accumulatedCopySize, options) default: err = fmt.Errorf("Unexpected kind: %s", op.Kind()) } if err != nil { return nil, err } } data, err := json.MarshalEscaped(pd, options.EscapeHTML) if err != nil { return nil, err } if indent == "" { return data, nil } var buf bytes.Buffer json.Indent(&buf, data, "", indent) return buf.Bytes(), nil } // From http://tools.ietf.org/html/rfc6901#section-4 : // // Evaluation of each reference token begins by decoding any escaped // character sequence. This is performed by first transforming any // occurrence of the sequence '~1' to '/', and then transforming any // occurrence of the sequence '~0' to '~'. var ( rfc6901Decoder = strings.NewReplacer("~1", "/", "~0", "~") ) func decodePatchKey(k string) string { return rfc6901Decoder.Replace(k) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/evanphx/json-patch/v5/internal/json/fuzz.go
vendor/github.com/evanphx/json-patch/v5/internal/json/fuzz.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. //go:build gofuzz package json import ( "fmt" ) func Fuzz(data []byte) (score int) { for _, ctor := range []func() any{ func() any { return new(any) }, func() any { return new(map[string]any) }, func() any { return new([]any) }, } { v := ctor() err := Unmarshal(data, v) if err != nil { continue } score = 1 m, err := Marshal(v) if err != nil { fmt.Printf("v=%#v\n", v) panic(err) } u := ctor() err = Unmarshal(m, u) if err != nil { fmt.Printf("v=%#v\n", v) fmt.Printf("m=%s\n", m) panic(err) } } return }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/evanphx/json-patch/v5/internal/json/indent.go
vendor/github.com/evanphx/json-patch/v5/internal/json/indent.go
// Copyright 2010 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" ) // Compact appends to dst the JSON-encoded src with // insignificant space characters elided. func Compact(dst *bytes.Buffer, src []byte) error { return compact(dst, src, false) } func compact(dst *bytes.Buffer, src []byte, escape bool) error { origLen := dst.Len() scan := newScanner() defer freeScanner(scan) start := 0 for i, c := range src { if escape && (c == '<' || c == '>' || c == '&') { if start < i { dst.Write(src[start:i]) } dst.WriteString(`\u00`) dst.WriteByte(hex[c>>4]) dst.WriteByte(hex[c&0xF]) start = i + 1 } // Convert U+2028 and U+2029 (E2 80 A8 and E2 80 A9). if escape && c == 0xE2 && i+2 < len(src) && src[i+1] == 0x80 && src[i+2]&^1 == 0xA8 { if start < i { dst.Write(src[start:i]) } dst.WriteString(`\u202`) dst.WriteByte(hex[src[i+2]&0xF]) start = i + 3 } v := scan.step(scan, c) if v >= scanSkipSpace { if v == scanError { break } if start < i { dst.Write(src[start:i]) } start = i + 1 } } if scan.eof() == scanError { dst.Truncate(origLen) return scan.err } if start < len(src) { dst.Write(src[start:]) } return nil } func newline(dst *bytes.Buffer, prefix, indent string, depth int) { dst.WriteByte('\n') dst.WriteString(prefix) for i := 0; i < depth; i++ { dst.WriteString(indent) } } // Indent appends to dst an indented form of the JSON-encoded src. // Each element in a JSON object or array begins on a new, // indented line beginning with prefix followed by one or more // copies of indent according to the indentation nesting. // The data appended to dst does not begin with the prefix nor // any indentation, to make it easier to embed inside other formatted JSON data. // Although leading space characters (space, tab, carriage return, newline) // at the beginning of src are dropped, trailing space characters // at the end of src are preserved and copied to dst. // For example, if src has no trailing spaces, neither will dst; // if src ends in a trailing newline, so will dst. func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error { origLen := dst.Len() scan := newScanner() defer freeScanner(scan) needIndent := false depth := 0 for _, c := range src { scan.bytes++ v := scan.step(scan, c) if v == scanSkipSpace { continue } if v == scanError { break } if needIndent && v != scanEndObject && v != scanEndArray { needIndent = false depth++ newline(dst, prefix, indent, depth) } // Emit semantically uninteresting bytes // (in particular, punctuation in strings) unmodified. if v == scanContinue { dst.WriteByte(c) continue } // Add spacing around real punctuation. switch c { case '{', '[': // delay indent so that empty object and array are formatted as {} and []. needIndent = true dst.WriteByte(c) case ',': dst.WriteByte(c) newline(dst, prefix, indent, depth) case ':': dst.WriteByte(c) dst.WriteByte(' ') case '}', ']': if needIndent { // suppress indent in empty object/array needIndent = false } else { depth-- newline(dst, prefix, indent, depth) } dst.WriteByte(c) default: dst.WriteByte(c) } } if scan.eof() == scanError { dst.Truncate(origLen) return scan.err } return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/evanphx/json-patch/v5/internal/json/fold.go
vendor/github.com/evanphx/json-patch/v5/internal/json/fold.go
// Copyright 2013 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" "unicode/utf8" ) const ( caseMask = ^byte(0x20) // Mask to ignore case in ASCII. kelvin = '\u212a' smallLongEss = '\u017f' ) // foldFunc returns one of four different case folding equivalence // functions, from most general (and slow) to fastest: // // 1) bytes.EqualFold, if the key s contains any non-ASCII UTF-8 // 2) equalFoldRight, if s contains special folding ASCII ('k', 'K', 's', 'S') // 3) asciiEqualFold, no special, but includes non-letters (including _) // 4) simpleLetterEqualFold, no specials, no non-letters. // // The letters S and K are special because they map to 3 runes, not just 2: // - S maps to s and to U+017F 'ſ' Latin small letter long s // - k maps to K and to U+212A 'K' Kelvin sign // // See https://play.golang.org/p/tTxjOc0OGo // // The returned function is specialized for matching against s and // should only be given s. It's not curried for performance reasons. func foldFunc(s []byte) func(s, t []byte) bool { nonLetter := false special := false // special letter for _, b := range s { if b >= utf8.RuneSelf { return bytes.EqualFold } upper := b & caseMask if upper < 'A' || upper > 'Z' { nonLetter = true } else if upper == 'K' || upper == 'S' { // See above for why these letters are special. special = true } } if special { return equalFoldRight } if nonLetter { return asciiEqualFold } return simpleLetterEqualFold } // equalFoldRight is a specialization of bytes.EqualFold when s is // known to be all ASCII (including punctuation), but contains an 's', // 'S', 'k', or 'K', requiring a Unicode fold on the bytes in t. // See comments on foldFunc. func equalFoldRight(s, t []byte) bool { for _, sb := range s { if len(t) == 0 { return false } tb := t[0] if tb < utf8.RuneSelf { if sb != tb { sbUpper := sb & caseMask if 'A' <= sbUpper && sbUpper <= 'Z' { if sbUpper != tb&caseMask { return false } } else { return false } } t = t[1:] continue } // sb is ASCII and t is not. t must be either kelvin // sign or long s; sb must be s, S, k, or K. tr, size := utf8.DecodeRune(t) switch sb { case 's', 'S': if tr != smallLongEss { return false } case 'k', 'K': if tr != kelvin { return false } default: return false } t = t[size:] } return len(t) == 0 } // asciiEqualFold is a specialization of bytes.EqualFold for use when // s is all ASCII (but may contain non-letters) and contains no // special-folding letters. // See comments on foldFunc. func asciiEqualFold(s, t []byte) bool { if len(s) != len(t) { return false } for i, sb := range s { tb := t[i] if sb == tb { continue } if ('a' <= sb && sb <= 'z') || ('A' <= sb && sb <= 'Z') { if sb&caseMask != tb&caseMask { return false } } else { return false } } return true } // simpleLetterEqualFold is a specialization of bytes.EqualFold for // use when s is all ASCII letters (no underscores, etc) and also // doesn't contain 'k', 'K', 's', or 'S'. // See comments on foldFunc. func simpleLetterEqualFold(s, t []byte) bool { if len(s) != len(t) { return false } for i, b := range s { if b&caseMask != t[i]&caseMask { 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/vendor/github.com/evanphx/json-patch/v5/internal/json/stream.go
vendor/github.com/evanphx/json-patch/v5/internal/json/stream.go
// Copyright 2010 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" "encoding/json" "io" ) // A Decoder reads and decodes JSON values from an input stream. type Decoder struct { r io.Reader buf []byte d decodeState scanp int // start of unread data in buf scanned int64 // amount of data already scanned scan scanner err error tokenState int tokenStack []int } // NewDecoder returns a new decoder that reads from r. // // The decoder introduces its own buffering and may // read data from r beyond the JSON values requested. func NewDecoder(r io.Reader) *Decoder { return &Decoder{r: r} } // UseNumber causes the Decoder to unmarshal a number into an interface{} as a // Number instead of as a float64. func (dec *Decoder) UseNumber() { dec.d.useNumber = true } // DisallowUnknownFields causes the Decoder to return an error when the destination // is a struct and the input contains object keys which do not match any // non-ignored, exported fields in the destination. func (dec *Decoder) DisallowUnknownFields() { dec.d.disallowUnknownFields = true } // Decode reads the next JSON-encoded value from its // input and stores it in the value pointed to by v. // // See the documentation for Unmarshal for details about // the conversion of JSON into a Go value. func (dec *Decoder) Decode(v any) error { if dec.err != nil { return dec.err } if err := dec.tokenPrepareForDecode(); err != nil { return err } if !dec.tokenValueAllowed() { return &SyntaxError{msg: "not at beginning of value", Offset: dec.InputOffset()} } // Read whole value into buffer. n, err := dec.readValue() if err != nil { return err } dec.d.init(dec.buf[dec.scanp : dec.scanp+n]) dec.scanp += n // Don't save err from unmarshal into dec.err: // the connection is still usable since we read a complete JSON // object from it before the error happened. err = dec.d.unmarshal(v) // fixup token streaming state dec.tokenValueEnd() return err } // Buffered returns a reader of the data remaining in the Decoder's // buffer. The reader is valid until the next call to Decode. func (dec *Decoder) Buffered() io.Reader { return bytes.NewReader(dec.buf[dec.scanp:]) } // readValue reads a JSON value into dec.buf. // It returns the length of the encoding. func (dec *Decoder) readValue() (int, error) { dec.scan.reset() scanp := dec.scanp var err error Input: // help the compiler see that scanp is never negative, so it can remove // some bounds checks below. for scanp >= 0 { // Look in the buffer for a new value. for ; scanp < len(dec.buf); scanp++ { c := dec.buf[scanp] dec.scan.bytes++ switch dec.scan.step(&dec.scan, c) { case scanEnd: // scanEnd is delayed one byte so we decrement // the scanner bytes count by 1 to ensure that // this value is correct in the next call of Decode. dec.scan.bytes-- break Input case scanEndObject, scanEndArray: // scanEnd is delayed one byte. // We might block trying to get that byte from src, // so instead invent a space byte. if stateEndValue(&dec.scan, ' ') == scanEnd { scanp++ break Input } case scanError: dec.err = dec.scan.err return 0, dec.scan.err } } // Did the last read have an error? // Delayed until now to allow buffer scan. if err != nil { if err == io.EOF { if dec.scan.step(&dec.scan, ' ') == scanEnd { break Input } if nonSpace(dec.buf) { err = io.ErrUnexpectedEOF } } dec.err = err return 0, err } n := scanp - dec.scanp err = dec.refill() scanp = dec.scanp + n } return scanp - dec.scanp, nil } func (dec *Decoder) refill() error { // Make room to read more into the buffer. // First slide down data already consumed. if dec.scanp > 0 { dec.scanned += int64(dec.scanp) n := copy(dec.buf, dec.buf[dec.scanp:]) dec.buf = dec.buf[:n] dec.scanp = 0 } // Grow buffer if not large enough. const minRead = 512 if cap(dec.buf)-len(dec.buf) < minRead { newBuf := make([]byte, len(dec.buf), 2*cap(dec.buf)+minRead) copy(newBuf, dec.buf) dec.buf = newBuf } // Read. Delay error for next iteration (after scan). n, err := dec.r.Read(dec.buf[len(dec.buf):cap(dec.buf)]) dec.buf = dec.buf[0 : len(dec.buf)+n] return err } func nonSpace(b []byte) bool { for _, c := range b { if !isSpace(c) { return true } } return false } // An Encoder writes JSON values to an output stream. type Encoder struct { w io.Writer err error escapeHTML bool indentBuf *bytes.Buffer indentPrefix string indentValue string } // NewEncoder returns a new encoder that writes to w. func NewEncoder(w io.Writer) *Encoder { return &Encoder{w: w, escapeHTML: true} } // Encode writes the JSON encoding of v to the stream, // followed by a newline character. // // See the documentation for Marshal for details about the // conversion of Go values to JSON. func (enc *Encoder) Encode(v any) error { if enc.err != nil { return enc.err } e := newEncodeState() defer encodeStatePool.Put(e) err := e.marshal(v, encOpts{escapeHTML: enc.escapeHTML}) if err != nil { return err } // Terminate each value with a newline. // This makes the output look a little nicer // when debugging, and some kind of space // is required if the encoded value was a number, // so that the reader knows there aren't more // digits coming. e.WriteByte('\n') b := e.Bytes() if enc.indentPrefix != "" || enc.indentValue != "" { if enc.indentBuf == nil { enc.indentBuf = new(bytes.Buffer) } enc.indentBuf.Reset() err = Indent(enc.indentBuf, b, enc.indentPrefix, enc.indentValue) if err != nil { return err } b = enc.indentBuf.Bytes() } if _, err = enc.w.Write(b); err != nil { enc.err = err } return err } // SetIndent instructs the encoder to format each subsequent encoded // value as if indented by the package-level function Indent(dst, src, prefix, indent). // Calling SetIndent("", "") disables indentation. func (enc *Encoder) SetIndent(prefix, indent string) { enc.indentPrefix = prefix enc.indentValue = indent } // SetEscapeHTML specifies whether problematic HTML characters // should be escaped inside JSON quoted strings. // The default behavior is to escape &, <, and > to \u0026, \u003c, and \u003e // to avoid certain safety problems that can arise when embedding JSON in HTML. // // In non-HTML settings where the escaping interferes with the readability // of the output, SetEscapeHTML(false) disables this behavior. func (enc *Encoder) SetEscapeHTML(on bool) { enc.escapeHTML = on } // RawMessage is a raw encoded JSON value. // It implements Marshaler and Unmarshaler and can // be used to delay JSON decoding or precompute a JSON encoding. type RawMessage = json.RawMessage // A Token holds a value of one of these types: // // Delim, for the four JSON delimiters [ ] { } // bool, for JSON booleans // float64, for JSON numbers // Number, for JSON numbers // string, for JSON string literals // nil, for JSON null type Token any const ( tokenTopValue = iota tokenArrayStart tokenArrayValue tokenArrayComma tokenObjectStart tokenObjectKey tokenObjectColon tokenObjectValue tokenObjectComma ) // advance tokenstate from a separator state to a value state func (dec *Decoder) tokenPrepareForDecode() error { // Note: Not calling peek before switch, to avoid // putting peek into the standard Decode path. // peek is only called when using the Token API. switch dec.tokenState { case tokenArrayComma: c, err := dec.peek() if err != nil { return err } if c != ',' { return &SyntaxError{"expected comma after array element", dec.InputOffset()} } dec.scanp++ dec.tokenState = tokenArrayValue case tokenObjectColon: c, err := dec.peek() if err != nil { return err } if c != ':' { return &SyntaxError{"expected colon after object key", dec.InputOffset()} } dec.scanp++ dec.tokenState = tokenObjectValue } return nil } func (dec *Decoder) tokenValueAllowed() bool { switch dec.tokenState { case tokenTopValue, tokenArrayStart, tokenArrayValue, tokenObjectValue: return true } return false } func (dec *Decoder) tokenValueEnd() { switch dec.tokenState { case tokenArrayStart, tokenArrayValue: dec.tokenState = tokenArrayComma case tokenObjectValue: dec.tokenState = tokenObjectComma } } // A Delim is a JSON array or object delimiter, one of [ ] { or }. type Delim rune func (d Delim) String() string { return string(d) } // Token returns the next JSON token in the input stream. // At the end of the input stream, Token returns nil, io.EOF. // // Token guarantees that the delimiters [ ] { } it returns are // properly nested and matched: if Token encounters an unexpected // delimiter in the input, it will return an error. // // The input stream consists of basic JSON values—bool, string, // number, and null—along with delimiters [ ] { } of type Delim // to mark the start and end of arrays and objects. // Commas and colons are elided. func (dec *Decoder) Token() (Token, error) { for { c, err := dec.peek() if err != nil { return nil, err } switch c { case '[': if !dec.tokenValueAllowed() { return dec.tokenError(c) } dec.scanp++ dec.tokenStack = append(dec.tokenStack, dec.tokenState) dec.tokenState = tokenArrayStart return Delim('['), nil case ']': if dec.tokenState != tokenArrayStart && dec.tokenState != tokenArrayComma { return dec.tokenError(c) } dec.scanp++ dec.tokenState = dec.tokenStack[len(dec.tokenStack)-1] dec.tokenStack = dec.tokenStack[:len(dec.tokenStack)-1] dec.tokenValueEnd() return Delim(']'), nil case '{': if !dec.tokenValueAllowed() { return dec.tokenError(c) } dec.scanp++ dec.tokenStack = append(dec.tokenStack, dec.tokenState) dec.tokenState = tokenObjectStart return Delim('{'), nil case '}': if dec.tokenState != tokenObjectStart && dec.tokenState != tokenObjectComma { return dec.tokenError(c) } dec.scanp++ dec.tokenState = dec.tokenStack[len(dec.tokenStack)-1] dec.tokenStack = dec.tokenStack[:len(dec.tokenStack)-1] dec.tokenValueEnd() return Delim('}'), nil case ':': if dec.tokenState != tokenObjectColon { return dec.tokenError(c) } dec.scanp++ dec.tokenState = tokenObjectValue continue case ',': if dec.tokenState == tokenArrayComma { dec.scanp++ dec.tokenState = tokenArrayValue continue } if dec.tokenState == tokenObjectComma { dec.scanp++ dec.tokenState = tokenObjectKey continue } return dec.tokenError(c) case '"': if dec.tokenState == tokenObjectStart || dec.tokenState == tokenObjectKey { var x string old := dec.tokenState dec.tokenState = tokenTopValue err := dec.Decode(&x) dec.tokenState = old if err != nil { return nil, err } dec.tokenState = tokenObjectColon return x, nil } fallthrough default: if !dec.tokenValueAllowed() { return dec.tokenError(c) } var x any if err := dec.Decode(&x); err != nil { return nil, err } return x, nil } } } func (dec *Decoder) tokenError(c byte) (Token, error) { var context string switch dec.tokenState { case tokenTopValue: context = " looking for beginning of value" case tokenArrayStart, tokenArrayValue, tokenObjectValue: context = " looking for beginning of value" case tokenArrayComma: context = " after array element" case tokenObjectKey: context = " looking for beginning of object key string" case tokenObjectColon: context = " after object key" case tokenObjectComma: context = " after object key:value pair" } return nil, &SyntaxError{"invalid character " + quoteChar(c) + context, dec.InputOffset()} } // More reports whether there is another element in the // current array or object being parsed. func (dec *Decoder) More() bool { c, err := dec.peek() return err == nil && c != ']' && c != '}' } func (dec *Decoder) peek() (byte, error) { var err error for { for i := dec.scanp; i < len(dec.buf); i++ { c := dec.buf[i] if isSpace(c) { continue } dec.scanp = i return c, nil } // buffer has been scanned, now report any error if err != nil { return 0, err } err = dec.refill() } } // InputOffset returns the input stream byte offset of the current decoder position. // The offset gives the location of the end of the most recently returned token // and the beginning of the next token. func (dec *Decoder) InputOffset() int64 { return dec.scanned + int64(dec.scanp) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/evanphx/json-patch/v5/internal/json/tags.go
vendor/github.com/evanphx/json-patch/v5/internal/json/tags.go
// Copyright 2011 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 ( "strings" ) // tagOptions is the string following a comma in a struct field's "json" // tag, or the empty string. It does not include the leading comma. type tagOptions string // parseTag splits a struct field's json tag into its name and // comma-separated options. func parseTag(tag string) (string, tagOptions) { tag, opt, _ := strings.Cut(tag, ",") return tag, tagOptions(opt) } // Contains reports whether a comma-separated list of options // contains a particular substr flag. substr must be surrounded by a // string boundary or commas. func (o tagOptions) Contains(optionName string) bool { if len(o) == 0 { return false } s := string(o) for s != "" { var name string name, s, _ = strings.Cut(s, ",") if name == optionName { return true } } return false }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/evanphx/json-patch/v5/internal/json/encode.go
vendor/github.com/evanphx/json-patch/v5/internal/json/encode.go
// Copyright 2010 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 implements encoding and decoding of JSON as defined in // RFC 7159. The mapping between JSON and Go values is described // in the documentation for the Marshal and Unmarshal functions. // // See "JSON and Go" for an introduction to this package: // https://golang.org/doc/articles/json_and_go.html package json import ( "bytes" "encoding" "encoding/base64" "fmt" "math" "reflect" "sort" "strconv" "strings" "sync" "unicode" "unicode/utf8" ) // Marshal returns the JSON encoding of v. // // Marshal traverses the value v recursively. // If an encountered value implements the Marshaler interface // and is not a nil pointer, Marshal calls its MarshalJSON method // to produce JSON. If no MarshalJSON method is present but the // value implements encoding.TextMarshaler instead, Marshal calls // its MarshalText method and encodes the result as a JSON string. // The nil pointer exception is not strictly necessary // but mimics a similar, necessary exception in the behavior of // UnmarshalJSON. // // Otherwise, Marshal uses the following type-dependent default encodings: // // Boolean values encode as JSON booleans. // // Floating point, integer, and Number values encode as JSON numbers. // // String values encode as JSON strings coerced to valid UTF-8, // replacing invalid bytes with the Unicode replacement rune. // So that the JSON will be safe to embed inside HTML <script> tags, // the string is encoded using HTMLEscape, // which replaces "<", ">", "&", U+2028, and U+2029 are escaped // to "\u003c","\u003e", "\u0026", "\u2028", and "\u2029". // This replacement can be disabled when using an Encoder, // by calling SetEscapeHTML(false). // // Array and slice values encode as JSON arrays, except that // []byte encodes as a base64-encoded string, and a nil slice // encodes as the null JSON value. // // Struct values encode as JSON objects. // Each exported struct field becomes a member of the object, using the // field name as the object key, unless the field is omitted for one of the // reasons given below. // // The encoding of each struct field can be customized by the format string // stored under the "json" key in the struct field's tag. // The format string gives the name of the field, possibly followed by a // comma-separated list of options. The name may be empty in order to // specify options without overriding the default field name. // // The "omitempty" option specifies that the field should be omitted // from the encoding if the field has an empty value, defined as // false, 0, a nil pointer, a nil interface value, and any empty array, // slice, map, or string. // // As a special case, if the field tag is "-", the field is always omitted. // Note that a field with name "-" can still be generated using the tag "-,". // // Examples of struct field tags and their meanings: // // // Field appears in JSON as key "myName". // Field int `json:"myName"` // // // Field appears in JSON as key "myName" and // // the field is omitted from the object if its value is empty, // // as defined above. // Field int `json:"myName,omitempty"` // // // Field appears in JSON as key "Field" (the default), but // // the field is skipped if empty. // // Note the leading comma. // Field int `json:",omitempty"` // // // Field is ignored by this package. // Field int `json:"-"` // // // Field appears in JSON as key "-". // Field int `json:"-,"` // // The "string" option signals that a field is stored as JSON inside a // JSON-encoded string. It applies only to fields of string, floating point, // integer, or boolean types. This extra level of encoding is sometimes used // when communicating with JavaScript programs: // // Int64String int64 `json:",string"` // // The key name will be used if it's a non-empty string consisting of // only Unicode letters, digits, and ASCII punctuation except quotation // marks, backslash, and comma. // // Anonymous struct fields are usually marshaled as if their inner exported fields // were fields in the outer struct, subject to the usual Go visibility rules amended // as described in the next paragraph. // An anonymous struct field with a name given in its JSON tag is treated as // having that name, rather than being anonymous. // An anonymous struct field of interface type is treated the same as having // that type as its name, rather than being anonymous. // // The Go visibility rules for struct fields are amended for JSON when // deciding which field to marshal or unmarshal. If there are // multiple fields at the same level, and that level is the least // nested (and would therefore be the nesting level selected by the // usual Go rules), the following extra rules apply: // // 1) Of those fields, if any are JSON-tagged, only tagged fields are considered, // even if there are multiple untagged fields that would otherwise conflict. // // 2) If there is exactly one field (tagged or not according to the first rule), that is selected. // // 3) Otherwise there are multiple fields, and all are ignored; no error occurs. // // Handling of anonymous struct fields is new in Go 1.1. // Prior to Go 1.1, anonymous struct fields were ignored. To force ignoring of // an anonymous struct field in both current and earlier versions, give the field // a JSON tag of "-". // // Map values encode as JSON objects. The map's key type must either be a // string, an integer type, or implement encoding.TextMarshaler. The map keys // are sorted and used as JSON object keys by applying the following rules, // subject to the UTF-8 coercion described for string values above: // - keys of any string type are used directly // - encoding.TextMarshalers are marshaled // - integer keys are converted to strings // // Pointer values encode as the value pointed to. // A nil pointer encodes as the null JSON value. // // Interface values encode as the value contained in the interface. // A nil interface value encodes as the null JSON value. // // Channel, complex, and function values cannot be encoded in JSON. // Attempting to encode such a value causes Marshal to return // an UnsupportedTypeError. // // JSON cannot represent cyclic data structures and Marshal does not // handle them. Passing cyclic structures to Marshal will result in // an error. func Marshal(v any) ([]byte, error) { e := newEncodeState() defer encodeStatePool.Put(e) err := e.marshal(v, encOpts{escapeHTML: true}) if err != nil { return nil, err } buf := append([]byte(nil), e.Bytes()...) return buf, nil } func MarshalEscaped(v any, escape bool) ([]byte, error) { e := newEncodeState() defer encodeStatePool.Put(e) err := e.marshal(v, encOpts{escapeHTML: escape}) if err != nil { return nil, err } buf := append([]byte(nil), e.Bytes()...) return buf, nil } // MarshalIndent is like Marshal but applies Indent to format the output. // Each JSON element in the output will begin on a new line beginning with prefix // followed by one or more copies of indent according to the indentation nesting. func MarshalIndent(v any, prefix, indent string) ([]byte, error) { b, err := Marshal(v) if err != nil { return nil, err } var buf bytes.Buffer err = Indent(&buf, b, prefix, indent) if err != nil { return nil, err } return buf.Bytes(), nil } // HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029 // characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029 // so that the JSON will be safe to embed inside HTML <script> tags. // For historical reasons, web browsers don't honor standard HTML // escaping within <script> tags, so an alternative JSON encoding must // be used. func HTMLEscape(dst *bytes.Buffer, src []byte) { // The characters can only appear in string literals, // so just scan the string one byte at a time. start := 0 for i, c := range src { if c == '<' || c == '>' || c == '&' { if start < i { dst.Write(src[start:i]) } dst.WriteString(`\u00`) dst.WriteByte(hex[c>>4]) dst.WriteByte(hex[c&0xF]) start = i + 1 } // Convert U+2028 and U+2029 (E2 80 A8 and E2 80 A9). if c == 0xE2 && i+2 < len(src) && src[i+1] == 0x80 && src[i+2]&^1 == 0xA8 { if start < i { dst.Write(src[start:i]) } dst.WriteString(`\u202`) dst.WriteByte(hex[src[i+2]&0xF]) start = i + 3 } } if start < len(src) { dst.Write(src[start:]) } } // Marshaler is the interface implemented by types that // can marshal themselves into valid JSON. type Marshaler interface { MarshalJSON() ([]byte, error) } type RedirectMarshaler interface { RedirectMarshalJSON() (any, error) } type TrustMarshaler interface { TrustMarshalJSON(b *bytes.Buffer) error } // An UnsupportedTypeError is returned by Marshal when attempting // to encode an unsupported value type. type UnsupportedTypeError struct { Type reflect.Type } func (e *UnsupportedTypeError) Error() string { return "json: unsupported type: " + e.Type.String() } // An UnsupportedValueError is returned by Marshal when attempting // to encode an unsupported value. type UnsupportedValueError struct { Value reflect.Value Str string } func (e *UnsupportedValueError) Error() string { return "json: unsupported value: " + e.Str } // Before Go 1.2, an InvalidUTF8Error was returned by Marshal when // attempting to encode a string value with invalid UTF-8 sequences. // As of Go 1.2, Marshal instead coerces the string to valid UTF-8 by // replacing invalid bytes with the Unicode replacement rune U+FFFD. // // Deprecated: No longer used; kept for compatibility. type InvalidUTF8Error struct { S string // the whole string value that caused the error } func (e *InvalidUTF8Error) Error() string { return "json: invalid UTF-8 in string: " + strconv.Quote(e.S) } // A MarshalerError represents an error from calling a MarshalJSON or MarshalText method. type MarshalerError struct { Type reflect.Type Err error sourceFunc string } func (e *MarshalerError) Error() string { srcFunc := e.sourceFunc if srcFunc == "" { srcFunc = "MarshalJSON" } return "json: error calling " + srcFunc + " for type " + e.Type.String() + ": " + e.Err.Error() } // Unwrap returns the underlying error. func (e *MarshalerError) Unwrap() error { return e.Err } var hex = "0123456789abcdef" // An encodeState encodes JSON into a bytes.Buffer. type encodeState struct { bytes.Buffer // accumulated output scratch [64]byte // Keep track of what pointers we've seen in the current recursive call // path, to avoid cycles that could lead to a stack overflow. Only do // the relatively expensive map operations if ptrLevel is larger than // startDetectingCyclesAfter, so that we skip the work if we're within a // reasonable amount of nested pointers deep. ptrLevel uint ptrSeen map[any]struct{} } const startDetectingCyclesAfter = 1000 var encodeStatePool sync.Pool func newEncodeState() *encodeState { if v := encodeStatePool.Get(); v != nil { e := v.(*encodeState) e.Reset() if len(e.ptrSeen) > 0 { panic("ptrEncoder.encode should have emptied ptrSeen via defers") } e.ptrLevel = 0 return e } return &encodeState{ptrSeen: make(map[any]struct{})} } // jsonError is an error wrapper type for internal use only. // Panics with errors are wrapped in jsonError so that the top-level recover // can distinguish intentional panics from this package. type jsonError struct{ error } func (e *encodeState) marshal(v any, opts encOpts) (err error) { defer func() { if r := recover(); r != nil { if je, ok := r.(jsonError); ok { err = je.error } else { panic(r) } } }() e.reflectValue(reflect.ValueOf(v), opts) return nil } // error aborts the encoding by panicking with err wrapped in jsonError. func (e *encodeState) error(err error) { panic(jsonError{err}) } func isEmptyValue(v reflect.Value) bool { switch v.Kind() { case reflect.Array, reflect.Map, reflect.Slice, reflect.String: return v.Len() == 0 case reflect.Bool: return !v.Bool() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Int() == 0 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return v.Uint() == 0 case reflect.Float32, reflect.Float64: return v.Float() == 0 case reflect.Interface, reflect.Pointer: return v.IsNil() } return false } func (e *encodeState) reflectValue(v reflect.Value, opts encOpts) { valueEncoder(v)(e, v, opts) } type encOpts struct { // quoted causes primitive fields to be encoded inside JSON strings. quoted bool // escapeHTML causes '<', '>', and '&' to be escaped in JSON strings. escapeHTML bool } type encoderFunc func(e *encodeState, v reflect.Value, opts encOpts) var encoderCache sync.Map // map[reflect.Type]encoderFunc func valueEncoder(v reflect.Value) encoderFunc { if !v.IsValid() { return invalidValueEncoder } return typeEncoder(v.Type()) } func typeEncoder(t reflect.Type) encoderFunc { if fi, ok := encoderCache.Load(t); ok { return fi.(encoderFunc) } // To deal with recursive types, populate the map with an // indirect func before we build it. This type waits on the // real func (f) to be ready and then calls it. This indirect // func is only used for recursive types. var ( wg sync.WaitGroup f encoderFunc ) wg.Add(1) fi, loaded := encoderCache.LoadOrStore(t, encoderFunc(func(e *encodeState, v reflect.Value, opts encOpts) { wg.Wait() f(e, v, opts) })) if loaded { return fi.(encoderFunc) } // Compute the real encoder and replace the indirect func with it. f = newTypeEncoder(t, true) wg.Done() encoderCache.Store(t, f) return f } var ( marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() redirMarshalerType = reflect.TypeOf((*RedirectMarshaler)(nil)).Elem() trustMarshalerType = reflect.TypeOf((*TrustMarshaler)(nil)).Elem() textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() ) // newTypeEncoder constructs an encoderFunc for a type. // The returned encoder only checks CanAddr when allowAddr is true. func newTypeEncoder(t reflect.Type, allowAddr bool) encoderFunc { if t.Implements(redirMarshalerType) { return redirMarshalerEncoder } if t.Implements(trustMarshalerType) { return marshalerTrustEncoder } // If we have a non-pointer value whose type implements // Marshaler with a value receiver, then we're better off taking // the address of the value - otherwise we end up with an // allocation as we cast the value to an interface. if t.Kind() != reflect.Pointer && allowAddr && reflect.PointerTo(t).Implements(marshalerType) { return newCondAddrEncoder(addrMarshalerEncoder, newTypeEncoder(t, false)) } if t.Implements(marshalerType) { return marshalerEncoder } if t.Kind() != reflect.Pointer && allowAddr && reflect.PointerTo(t).Implements(textMarshalerType) { return newCondAddrEncoder(addrTextMarshalerEncoder, newTypeEncoder(t, false)) } if t.Implements(textMarshalerType) { return textMarshalerEncoder } switch t.Kind() { case reflect.Bool: return boolEncoder case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return intEncoder case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return uintEncoder case reflect.Float32: return float32Encoder case reflect.Float64: return float64Encoder case reflect.String: return stringEncoder case reflect.Interface: return interfaceEncoder case reflect.Struct: return newStructEncoder(t) case reflect.Map: return newMapEncoder(t) case reflect.Slice: return newSliceEncoder(t) case reflect.Array: return newArrayEncoder(t) case reflect.Pointer: return newPtrEncoder(t) default: return unsupportedTypeEncoder } } func invalidValueEncoder(e *encodeState, v reflect.Value, _ encOpts) { e.WriteString("null") } func redirMarshalerEncoder(e *encodeState, v reflect.Value, opts encOpts) { if v.Kind() == reflect.Pointer && v.IsNil() { e.WriteString("null") return } m, ok := v.Interface().(RedirectMarshaler) if !ok { e.WriteString("null") return } iv, err := m.RedirectMarshalJSON() if err != nil { e.error(&MarshalerError{v.Type(), err, "RedirectMarshalJSON"}) return } e.marshal(iv, opts) } func marshalerTrustEncoder(e *encodeState, v reflect.Value, opts encOpts) { if v.Kind() == reflect.Pointer && v.IsNil() { e.WriteString("null") return } m, ok := v.Interface().(TrustMarshaler) if !ok { e.WriteString("null") return } err := m.TrustMarshalJSON(&e.Buffer) if err == nil { //_, err = e.Buffer.Write(b) // copy JSON into buffer, checking validity. //err = compact(&e.Buffer, b, opts.escapeHTML) } if err != nil { e.error(&MarshalerError{v.Type(), err, "MarshalJSON"}) } } func marshalerEncoder(e *encodeState, v reflect.Value, opts encOpts) { if v.Kind() == reflect.Pointer && v.IsNil() { e.WriteString("null") return } m, ok := v.Interface().(Marshaler) if !ok { e.WriteString("null") return } b, err := m.MarshalJSON() if err == nil { // copy JSON into buffer, checking validity. err = compact(&e.Buffer, b, opts.escapeHTML) } if err != nil { e.error(&MarshalerError{v.Type(), err, "MarshalJSON"}) } } func addrMarshalerEncoder(e *encodeState, v reflect.Value, opts encOpts) { va := v.Addr() if va.IsNil() { e.WriteString("null") return } m := va.Interface().(Marshaler) b, err := m.MarshalJSON() if err == nil { // copy JSON into buffer, checking validity. err = compact(&e.Buffer, b, opts.escapeHTML) } if err != nil { e.error(&MarshalerError{v.Type(), err, "MarshalJSON"}) } } func textMarshalerEncoder(e *encodeState, v reflect.Value, opts encOpts) { if v.Kind() == reflect.Pointer && v.IsNil() { e.WriteString("null") return } m, ok := v.Interface().(encoding.TextMarshaler) if !ok { e.WriteString("null") return } b, err := m.MarshalText() if err != nil { e.error(&MarshalerError{v.Type(), err, "MarshalText"}) } e.stringBytes(b, opts.escapeHTML) } func addrTextMarshalerEncoder(e *encodeState, v reflect.Value, opts encOpts) { va := v.Addr() if va.IsNil() { e.WriteString("null") return } m := va.Interface().(encoding.TextMarshaler) b, err := m.MarshalText() if err != nil { e.error(&MarshalerError{v.Type(), err, "MarshalText"}) } e.stringBytes(b, opts.escapeHTML) } func boolEncoder(e *encodeState, v reflect.Value, opts encOpts) { if opts.quoted { e.WriteByte('"') } if v.Bool() { e.WriteString("true") } else { e.WriteString("false") } if opts.quoted { e.WriteByte('"') } } func intEncoder(e *encodeState, v reflect.Value, opts encOpts) { b := strconv.AppendInt(e.scratch[:0], v.Int(), 10) if opts.quoted { e.WriteByte('"') } e.Write(b) if opts.quoted { e.WriteByte('"') } } func uintEncoder(e *encodeState, v reflect.Value, opts encOpts) { b := strconv.AppendUint(e.scratch[:0], v.Uint(), 10) if opts.quoted { e.WriteByte('"') } e.Write(b) if opts.quoted { e.WriteByte('"') } } type floatEncoder int // number of bits func (bits floatEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) { f := v.Float() if math.IsInf(f, 0) || math.IsNaN(f) { e.error(&UnsupportedValueError{v, strconv.FormatFloat(f, 'g', -1, int(bits))}) } // Convert as if by ES6 number to string conversion. // This matches most other JSON generators. // See golang.org/issue/6384 and golang.org/issue/14135. // Like fmt %g, but the exponent cutoffs are different // and exponents themselves are not padded to two digits. b := e.scratch[:0] abs := math.Abs(f) fmt := byte('f') // Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right. if abs != 0 { if bits == 64 && (abs < 1e-6 || abs >= 1e21) || bits == 32 && (float32(abs) < 1e-6 || float32(abs) >= 1e21) { fmt = 'e' } } b = strconv.AppendFloat(b, f, fmt, -1, int(bits)) if fmt == 'e' { // clean up e-09 to e-9 n := len(b) if n >= 4 && b[n-4] == 'e' && b[n-3] == '-' && b[n-2] == '0' { b[n-2] = b[n-1] b = b[:n-1] } } if opts.quoted { e.WriteByte('"') } e.Write(b) if opts.quoted { e.WriteByte('"') } } var ( float32Encoder = (floatEncoder(32)).encode float64Encoder = (floatEncoder(64)).encode ) func stringEncoder(e *encodeState, v reflect.Value, opts encOpts) { if v.Type() == numberType { numStr := v.String() // In Go1.5 the empty string encodes to "0", while this is not a valid number literal // we keep compatibility so check validity after this. if numStr == "" { numStr = "0" // Number's zero-val } if !isValidNumber(numStr) { e.error(fmt.Errorf("json: invalid number literal %q", numStr)) } if opts.quoted { e.WriteByte('"') } e.WriteString(numStr) if opts.quoted { e.WriteByte('"') } return } if opts.quoted { e2 := newEncodeState() // Since we encode the string twice, we only need to escape HTML // the first time. e2.string(v.String(), opts.escapeHTML) e.stringBytes(e2.Bytes(), false) encodeStatePool.Put(e2) } else { e.string(v.String(), opts.escapeHTML) } } // isValidNumber reports whether s is a valid JSON number literal. func isValidNumber(s string) bool { // This function implements the JSON numbers grammar. // See https://tools.ietf.org/html/rfc7159#section-6 // and https://www.json.org/img/number.png if s == "" { return false } // Optional - if s[0] == '-' { s = s[1:] if s == "" { return false } } // Digits switch { default: return false case s[0] == '0': s = s[1:] case '1' <= s[0] && s[0] <= '9': s = s[1:] for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { s = s[1:] } } // . followed by 1 or more digits. if len(s) >= 2 && s[0] == '.' && '0' <= s[1] && s[1] <= '9' { s = s[2:] for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { s = s[1:] } } // 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:] if s[0] == '+' || s[0] == '-' { s = s[1:] if s == "" { return false } } for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { s = s[1:] } } // Make sure we are at the end. return s == "" } func interfaceEncoder(e *encodeState, v reflect.Value, opts encOpts) { if v.IsNil() { e.WriteString("null") return } e.reflectValue(v.Elem(), opts) } func unsupportedTypeEncoder(e *encodeState, v reflect.Value, _ encOpts) { e.error(&UnsupportedTypeError{v.Type()}) } type structEncoder struct { fields structFields } type structFields struct { list []field nameIndex map[string]int } func (se structEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) { next := byte('{') FieldLoop: for i := range se.fields.list { f := &se.fields.list[i] // Find the nested struct field by following f.index. fv := v for _, i := range f.index { if fv.Kind() == reflect.Pointer { if fv.IsNil() { continue FieldLoop } fv = fv.Elem() } fv = fv.Field(i) } if f.omitEmpty && isEmptyValue(fv) { continue } e.WriteByte(next) next = ',' if opts.escapeHTML { e.WriteString(f.nameEscHTML) } else { e.WriteString(f.nameNonEsc) } opts.quoted = f.quoted f.encoder(e, fv, opts) } if next == '{' { e.WriteString("{}") } else { e.WriteByte('}') } } func newStructEncoder(t reflect.Type) encoderFunc { se := structEncoder{fields: cachedTypeFields(t)} return se.encode } type mapEncoder struct { elemEnc encoderFunc } func (me mapEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) { if v.IsNil() { e.WriteString("null") return } if e.ptrLevel++; e.ptrLevel > startDetectingCyclesAfter { // We're a large number of nested ptrEncoder.encode calls deep; // start checking if we've run into a pointer cycle. ptr := v.UnsafePointer() if _, ok := e.ptrSeen[ptr]; ok { e.error(&UnsupportedValueError{v, fmt.Sprintf("encountered a cycle via %s", v.Type())}) } e.ptrSeen[ptr] = struct{}{} defer delete(e.ptrSeen, ptr) } e.WriteByte('{') // Extract and sort the keys. sv := make([]reflectWithString, v.Len()) mi := v.MapRange() for i := 0; mi.Next(); i++ { sv[i].k = mi.Key() sv[i].v = mi.Value() if err := sv[i].resolve(); err != nil { e.error(fmt.Errorf("json: encoding error for type %q: %q", v.Type().String(), err.Error())) } } sort.Slice(sv, func(i, j int) bool { return sv[i].ks < sv[j].ks }) for i, kv := range sv { if i > 0 { e.WriteByte(',') } e.string(kv.ks, opts.escapeHTML) e.WriteByte(':') me.elemEnc(e, kv.v, opts) } e.WriteByte('}') e.ptrLevel-- } func newMapEncoder(t reflect.Type) encoderFunc { switch t.Key().Kind() { case reflect.String, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: default: if !t.Key().Implements(textMarshalerType) { return unsupportedTypeEncoder } } me := mapEncoder{typeEncoder(t.Elem())} return me.encode } func encodeByteSlice(e *encodeState, v reflect.Value, _ encOpts) { if v.IsNil() { e.WriteString("null") return } s := v.Bytes() e.WriteByte('"') encodedLen := base64.StdEncoding.EncodedLen(len(s)) if encodedLen <= len(e.scratch) { // If the encoded bytes fit in e.scratch, avoid an extra // allocation and use the cheaper Encoding.Encode. dst := e.scratch[:encodedLen] base64.StdEncoding.Encode(dst, s) e.Write(dst) } else if encodedLen <= 1024 { // The encoded bytes are short enough to allocate for, and // Encoding.Encode is still cheaper. dst := make([]byte, encodedLen) base64.StdEncoding.Encode(dst, s) e.Write(dst) } else { // The encoded bytes are too long to cheaply allocate, and // Encoding.Encode is no longer noticeably cheaper. enc := base64.NewEncoder(base64.StdEncoding, e) enc.Write(s) enc.Close() } e.WriteByte('"') } // sliceEncoder just wraps an arrayEncoder, checking to make sure the value isn't nil. type sliceEncoder struct { arrayEnc encoderFunc } func (se sliceEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) { if v.IsNil() { e.WriteString("null") return } if e.ptrLevel++; e.ptrLevel > startDetectingCyclesAfter { // We're a large number of nested ptrEncoder.encode calls deep; // start checking if we've run into a pointer cycle. // Here we use a struct to memorize the pointer to the first element of the slice // and its length. ptr := struct { ptr interface{} // always an unsafe.Pointer, but avoids a dependency on package unsafe len int }{v.UnsafePointer(), v.Len()} if _, ok := e.ptrSeen[ptr]; ok { e.error(&UnsupportedValueError{v, fmt.Sprintf("encountered a cycle via %s", v.Type())}) } e.ptrSeen[ptr] = struct{}{} defer delete(e.ptrSeen, ptr) } se.arrayEnc(e, v, opts) e.ptrLevel-- } func newSliceEncoder(t reflect.Type) encoderFunc { // Byte slices get special treatment; arrays don't. if t.Elem().Kind() == reflect.Uint8 { p := reflect.PointerTo(t.Elem()) if !p.Implements(marshalerType) && !p.Implements(textMarshalerType) { return encodeByteSlice } } enc := sliceEncoder{newArrayEncoder(t)} return enc.encode } type arrayEncoder struct { elemEnc encoderFunc } func (ae arrayEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) { e.WriteByte('[') n := v.Len() for i := 0; i < n; i++ { if i > 0 { e.WriteByte(',') } ae.elemEnc(e, v.Index(i), opts) } e.WriteByte(']') } func newArrayEncoder(t reflect.Type) encoderFunc { enc := arrayEncoder{typeEncoder(t.Elem())} return enc.encode } type ptrEncoder struct { elemEnc encoderFunc } func (pe ptrEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) { if v.IsNil() { e.WriteString("null") return } if e.ptrLevel++; e.ptrLevel > startDetectingCyclesAfter { // We're a large number of nested ptrEncoder.encode calls deep; // start checking if we've run into a pointer cycle. ptr := v.Interface() if _, ok := e.ptrSeen[ptr]; ok { e.error(&UnsupportedValueError{v, fmt.Sprintf("encountered a cycle via %s", v.Type())}) } e.ptrSeen[ptr] = struct{}{} defer delete(e.ptrSeen, ptr) } pe.elemEnc(e, v.Elem(), opts) e.ptrLevel-- } func newPtrEncoder(t reflect.Type) encoderFunc { enc := ptrEncoder{typeEncoder(t.Elem())} return enc.encode } type condAddrEncoder struct { canAddrEnc, elseEnc encoderFunc } func (ce condAddrEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) { if v.CanAddr() { ce.canAddrEnc(e, v, opts) } else { ce.elseEnc(e, v, opts) } } // newCondAddrEncoder returns an encoder that checks whether its value // CanAddr and delegates to canAddrEnc if so, else to elseEnc. func newCondAddrEncoder(canAddrEnc, elseEnc encoderFunc) encoderFunc { enc := condAddrEncoder{canAddrEnc: canAddrEnc, elseEnc: elseEnc} return enc.encode } func isValidTag(s string) bool { if s == "" { return false } for _, c := range s { switch { case strings.ContainsRune("!#$%&()*+-./:;<=>?@[]^_{|}~ ", c): // Backslash and quote chars are reserved, but // otherwise any punctuation chars are allowed // in a tag name. case !unicode.IsLetter(c) && !unicode.IsDigit(c): return false } } return true } func typeByIndex(t reflect.Type, index []int) reflect.Type { for _, i := range index { if t.Kind() == reflect.Pointer { t = t.Elem() } t = t.Field(i).Type } return t } type reflectWithString struct { k reflect.Value v reflect.Value ks string } func (w *reflectWithString) resolve() error { if w.k.Kind() == reflect.String { w.ks = w.k.String() return nil } if tm, ok := w.k.Interface().(encoding.TextMarshaler); ok { if w.k.Kind() == reflect.Pointer && w.k.IsNil() { return nil } buf, err := tm.MarshalText() w.ks = string(buf) return err } switch w.k.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: w.ks = strconv.FormatInt(w.k.Int(), 10) return nil case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: w.ks = strconv.FormatUint(w.k.Uint(), 10) return nil } panic("unexpected map key type") } // NOTE: keep in sync with stringBytes below. func (e *encodeState) string(s string, escapeHTML bool) { e.WriteByte('"') start := 0 for i := 0; i < len(s); { if b := s[i]; b < utf8.RuneSelf { if htmlSafeSet[b] || (!escapeHTML && safeSet[b]) { i++ continue } if start < i { e.WriteString(s[start:i]) } e.WriteByte('\\') switch b { case '\\', '"': e.WriteByte(b) case '\n': e.WriteByte('n') case '\r': e.WriteByte('r') case '\t': e.WriteByte('t') default: // This encodes bytes < 0x20 except for \t, \n and \r. // If escapeHTML is set, it also escapes <, >, and & // because they can lead to security holes when // user-controlled strings are rendered into JSON // and served to some browsers. e.WriteString(`u00`) e.WriteByte(hex[b>>4]) e.WriteByte(hex[b&0xF]) } i++ start = i continue } c, size := utf8.DecodeRuneInString(s[i:]) if c == utf8.RuneError && size == 1 { if start < i { e.WriteString(s[start:i]) } e.WriteString(`\ufffd`) i += size start = i continue } // U+2028 is LINE SEPARATOR. // U+2029 is PARAGRAPH SEPARATOR. // They are both technically valid characters in JSON strings, // but don't work in JSONP, which has to be evaluated as JavaScript, // and can lead to security holes there. It is valid JSON to // escape them, so we do so unconditionally. // See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion. if c == '\u2028' || c == '\u2029' { if start < i { e.WriteString(s[start:i]) } e.WriteString(`\u202`) e.WriteByte(hex[c&0xF]) i += size start = i continue } i += size } if start < len(s) { e.WriteString(s[start:]) } e.WriteByte('"') } // NOTE: keep in sync with string above. func (e *encodeState) stringBytes(s []byte, escapeHTML bool) { e.WriteByte('"') start := 0 for i := 0; i < len(s); { if b := s[i]; b < utf8.RuneSelf { if htmlSafeSet[b] || (!escapeHTML && safeSet[b]) { i++ continue } if start < i { e.Write(s[start:i]) } e.WriteByte('\\') switch b { case '\\', '"': e.WriteByte(b) case '\n': e.WriteByte('n') case '\r': e.WriteByte('r') case '\t': e.WriteByte('t') default: // This encodes bytes < 0x20 except for \t, \n and \r. // If escapeHTML is set, it also escapes <, >, and & // because they can lead to security holes when
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/evanphx/json-patch/v5/internal/json/tables.go
vendor/github.com/evanphx/json-patch/v5/internal/json/tables.go
// Copyright 2016 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 "unicode/utf8" // safeSet holds the value true if the ASCII character with the given array // position can be represented inside a JSON string without any further // escaping. // // All values are true except for the ASCII control characters (0-31), the // double quote ("), and the backslash character ("\"). var safeSet = [utf8.RuneSelf]bool{ ' ': true, '!': true, '"': false, '#': true, '$': true, '%': true, '&': true, '\'': true, '(': true, ')': true, '*': true, '+': true, ',': true, '-': true, '.': true, '/': true, '0': true, '1': true, '2': true, '3': true, '4': true, '5': true, '6': true, '7': true, '8': true, '9': true, ':': true, ';': true, '<': true, '=': true, '>': true, '?': true, '@': true, 'A': true, 'B': true, 'C': true, 'D': true, 'E': true, 'F': true, 'G': true, 'H': true, 'I': true, 'J': true, 'K': true, 'L': true, 'M': true, 'N': true, 'O': true, 'P': true, 'Q': true, 'R': true, 'S': true, 'T': true, 'U': true, 'V': true, 'W': true, 'X': true, 'Y': true, 'Z': true, '[': true, '\\': false, ']': true, '^': true, '_': true, '`': true, 'a': true, 'b': true, 'c': true, 'd': true, 'e': true, 'f': true, 'g': true, 'h': true, 'i': true, 'j': true, 'k': true, 'l': true, 'm': true, 'n': true, 'o': true, 'p': true, 'q': true, 'r': true, 's': true, 't': true, 'u': true, 'v': true, 'w': true, 'x': true, 'y': true, 'z': true, '{': true, '|': true, '}': true, '~': true, '\u007f': true, } // htmlSafeSet holds the value true if the ASCII character with the given // array position can be safely represented inside a JSON string, embedded // inside of HTML <script> tags, without any additional escaping. // // All values are true except for the ASCII control characters (0-31), the // double quote ("), the backslash character ("\"), HTML opening and closing // tags ("<" and ">"), and the ampersand ("&"). var htmlSafeSet = [utf8.RuneSelf]bool{ ' ': true, '!': true, '"': false, '#': true, '$': true, '%': true, '&': false, '\'': true, '(': true, ')': true, '*': true, '+': true, ',': true, '-': true, '.': true, '/': true, '0': true, '1': true, '2': true, '3': true, '4': true, '5': true, '6': true, '7': true, '8': true, '9': true, ':': true, ';': true, '<': false, '=': true, '>': false, '?': true, '@': true, 'A': true, 'B': true, 'C': true, 'D': true, 'E': true, 'F': true, 'G': true, 'H': true, 'I': true, 'J': true, 'K': true, 'L': true, 'M': true, 'N': true, 'O': true, 'P': true, 'Q': true, 'R': true, 'S': true, 'T': true, 'U': true, 'V': true, 'W': true, 'X': true, 'Y': true, 'Z': true, '[': true, '\\': false, ']': true, '^': true, '_': true, '`': true, 'a': true, 'b': true, 'c': true, 'd': true, 'e': true, 'f': true, 'g': true, 'h': true, 'i': true, 'j': true, 'k': true, 'l': true, 'm': true, 'n': true, 'o': true, 'p': true, 'q': true, 'r': true, 's': true, 't': true, 'u': true, 'v': true, 'w': true, 'x': true, 'y': true, 'z': true, '{': true, '|': true, '}': true, '~': true, '\u007f': true, }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/evanphx/json-patch/v5/internal/json/scanner.go
vendor/github.com/evanphx/json-patch/v5/internal/json/scanner.go
// Copyright 2010 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 // JSON value parser state machine. // Just about at the limit of what is reasonable to write by hand. // Some parts are a bit tedious, but overall it nicely factors out the // otherwise common code from the multiple scanning functions // in this package (Compact, Indent, checkValid, etc). // // This file starts with two simple examples using the scanner // before diving into the scanner itself. import ( "strconv" "sync" ) // Valid reports whether data is a valid JSON encoding. func Valid(data []byte) bool { scan := newScanner() defer freeScanner(scan) return checkValid(data, scan) == nil } // checkValid verifies that data is valid JSON-encoded data. // scan is passed in for use by checkValid to avoid an allocation. // checkValid returns nil or a SyntaxError. func checkValid(data []byte, scan *scanner) error { scan.reset() for _, c := range data { scan.bytes++ if scan.step(scan, c) == scanError { return scan.err } } if scan.eof() == scanError { return scan.err } return nil } // A SyntaxError is a description of a JSON syntax error. // Unmarshal will return a SyntaxError if the JSON can't be parsed. type SyntaxError struct { msg string // description of error Offset int64 // error occurred after reading Offset bytes } func (e *SyntaxError) Error() string { return e.msg } // A scanner is a JSON scanning state machine. // Callers call scan.reset and then pass bytes in one at a time // by calling scan.step(&scan, c) for each byte. // The return value, referred to as an opcode, tells the // caller about significant parsing events like beginning // and ending literals, objects, and arrays, so that the // caller can follow along if it wishes. // The return value scanEnd indicates that a single top-level // JSON value has been completed, *before* the byte that // just got passed in. (The indication must be delayed in order // to recognize the end of numbers: is 123 a whole value or // the beginning of 12345e+6?). type scanner struct { // The step is a func to be called to execute the next transition. // Also tried using an integer constant and a single func // with a switch, but using the func directly was 10% faster // on a 64-bit Mac Mini, and it's nicer to read. step func(*scanner, byte) int // Reached end of top-level value. endTop bool // Stack of what we're in the middle of - array values, object keys, object values. parseState []int // Error that happened, if any. err error // total bytes consumed, updated by decoder.Decode (and deliberately // not set to zero by scan.reset) bytes int64 } var scannerPool = sync.Pool{ New: func() any { return &scanner{} }, } func newScanner() *scanner { scan := scannerPool.Get().(*scanner) // scan.reset by design doesn't set bytes to zero scan.bytes = 0 scan.reset() return scan } func freeScanner(scan *scanner) { // Avoid hanging on to too much memory in extreme cases. if len(scan.parseState) > 1024 { scan.parseState = nil } scannerPool.Put(scan) } // These values are returned by the state transition functions // assigned to scanner.state and the method scanner.eof. // They give details about the current state of the scan that // callers might be interested to know about. // It is okay to ignore the return value of any particular // call to scanner.state: if one call returns scanError, // every subsequent call will return scanError too. const ( // Continue. scanContinue = iota // uninteresting byte scanBeginLiteral // end implied by next result != scanContinue scanBeginObject // begin object scanObjectKey // just finished object key (string) scanObjectValue // just finished non-last object value scanEndObject // end object (implies scanObjectValue if possible) scanBeginArray // begin array scanArrayValue // just finished array value scanEndArray // end array (implies scanArrayValue if possible) scanSkipSpace // space byte; can skip; known to be last "continue" result // Stop. scanEnd // top-level value ended *before* this byte; known to be first "stop" result scanError // hit an error, scanner.err. ) // These values are stored in the parseState stack. // They give the current state of a composite value // being scanned. If the parser is inside a nested value // the parseState describes the nested state, outermost at entry 0. const ( parseObjectKey = iota // parsing object key (before colon) parseObjectValue // parsing object value (after colon) parseArrayValue // parsing array value ) // This limits the max nesting depth to prevent stack overflow. // This is permitted by https://tools.ietf.org/html/rfc7159#section-9 const maxNestingDepth = 10000 // reset prepares the scanner for use. // It must be called before calling s.step. func (s *scanner) reset() { s.step = stateBeginValue s.parseState = s.parseState[0:0] s.err = nil s.endTop = false } // eof tells the scanner that the end of input has been reached. // It returns a scan status just as s.step does. func (s *scanner) eof() int { if s.err != nil { return scanError } if s.endTop { return scanEnd } s.step(s, ' ') if s.endTop { return scanEnd } if s.err == nil { s.err = &SyntaxError{"unexpected end of JSON input", s.bytes} } return scanError } // pushParseState pushes a new parse state p onto the parse stack. // an error state is returned if maxNestingDepth was exceeded, otherwise successState is returned. func (s *scanner) pushParseState(c byte, newParseState int, successState int) int { s.parseState = append(s.parseState, newParseState) if len(s.parseState) <= maxNestingDepth { return successState } return s.error(c, "exceeded max depth") } // popParseState pops a parse state (already obtained) off the stack // and updates s.step accordingly. func (s *scanner) popParseState() { n := len(s.parseState) - 1 s.parseState = s.parseState[0:n] if n == 0 { s.step = stateEndTop s.endTop = true } else { s.step = stateEndValue } } func isSpace(c byte) bool { return c <= ' ' && (c == ' ' || c == '\t' || c == '\r' || c == '\n') } // stateBeginValueOrEmpty is the state after reading `[`. func stateBeginValueOrEmpty(s *scanner, c byte) int { if isSpace(c) { return scanSkipSpace } if c == ']' { return stateEndValue(s, c) } return stateBeginValue(s, c) } // stateBeginValue is the state at the beginning of the input. func stateBeginValue(s *scanner, c byte) int { if isSpace(c) { return scanSkipSpace } switch c { case '{': s.step = stateBeginStringOrEmpty return s.pushParseState(c, parseObjectKey, scanBeginObject) case '[': s.step = stateBeginValueOrEmpty return s.pushParseState(c, parseArrayValue, scanBeginArray) case '"': s.step = stateInString return scanBeginLiteral case '-': s.step = stateNeg return scanBeginLiteral case '0': // beginning of 0.123 s.step = state0 return scanBeginLiteral case 't': // beginning of true s.step = stateT return scanBeginLiteral case 'f': // beginning of false s.step = stateF return scanBeginLiteral case 'n': // beginning of null s.step = stateN return scanBeginLiteral } if '1' <= c && c <= '9' { // beginning of 1234.5 s.step = state1 return scanBeginLiteral } return s.error(c, "looking for beginning of value") } // stateBeginStringOrEmpty is the state after reading `{`. func stateBeginStringOrEmpty(s *scanner, c byte) int { if isSpace(c) { return scanSkipSpace } if c == '}' { n := len(s.parseState) s.parseState[n-1] = parseObjectValue return stateEndValue(s, c) } return stateBeginString(s, c) } // stateBeginString is the state after reading `{"key": value,`. func stateBeginString(s *scanner, c byte) int { if isSpace(c) { return scanSkipSpace } if c == '"' { s.step = stateInString return scanBeginLiteral } return s.error(c, "looking for beginning of object key string") } // stateEndValue is the state after completing a value, // such as after reading `{}` or `true` or `["x"`. func stateEndValue(s *scanner, c byte) int { n := len(s.parseState) if n == 0 { // Completed top-level before the current byte. s.step = stateEndTop s.endTop = true return stateEndTop(s, c) } if isSpace(c) { s.step = stateEndValue return scanSkipSpace } ps := s.parseState[n-1] switch ps { case parseObjectKey: if c == ':' { s.parseState[n-1] = parseObjectValue s.step = stateBeginValue return scanObjectKey } return s.error(c, "after object key") case parseObjectValue: if c == ',' { s.parseState[n-1] = parseObjectKey s.step = stateBeginString return scanObjectValue } if c == '}' { s.popParseState() return scanEndObject } return s.error(c, "after object key:value pair") case parseArrayValue: if c == ',' { s.step = stateBeginValue return scanArrayValue } if c == ']' { s.popParseState() return scanEndArray } return s.error(c, "after array element") } return s.error(c, "") } // stateEndTop is the state after finishing the top-level value, // such as after reading `{}` or `[1,2,3]`. // Only space characters should be seen now. func stateEndTop(s *scanner, c byte) int { if !isSpace(c) { // Complain about non-space byte on next call. s.error(c, "after top-level value") } return scanEnd } // stateInString is the state after reading `"`. func stateInString(s *scanner, c byte) int { if c == '"' { s.step = stateEndValue return scanContinue } if c == '\\' { s.step = stateInStringEsc return scanContinue } if c < 0x20 { return s.error(c, "in string literal") } return scanContinue } // stateInStringEsc is the state after reading `"\` during a quoted string. func stateInStringEsc(s *scanner, c byte) int { switch c { case 'b', 'f', 'n', 'r', 't', '\\', '/', '"': s.step = stateInString return scanContinue case 'u': s.step = stateInStringEscU return scanContinue } return s.error(c, "in string escape code") } // stateInStringEscU is the state after reading `"\u` during a quoted string. func stateInStringEscU(s *scanner, c byte) int { if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' { s.step = stateInStringEscU1 return scanContinue } // numbers return s.error(c, "in \\u hexadecimal character escape") } // stateInStringEscU1 is the state after reading `"\u1` during a quoted string. func stateInStringEscU1(s *scanner, c byte) int { if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' { s.step = stateInStringEscU12 return scanContinue } // numbers return s.error(c, "in \\u hexadecimal character escape") } // stateInStringEscU12 is the state after reading `"\u12` during a quoted string. func stateInStringEscU12(s *scanner, c byte) int { if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' { s.step = stateInStringEscU123 return scanContinue } // numbers return s.error(c, "in \\u hexadecimal character escape") } // stateInStringEscU123 is the state after reading `"\u123` during a quoted string. func stateInStringEscU123(s *scanner, c byte) int { if '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F' { s.step = stateInString return scanContinue } // numbers return s.error(c, "in \\u hexadecimal character escape") } // stateNeg is the state after reading `-` during a number. func stateNeg(s *scanner, c byte) int { if c == '0' { s.step = state0 return scanContinue } if '1' <= c && c <= '9' { s.step = state1 return scanContinue } return s.error(c, "in numeric literal") } // state1 is the state after reading a non-zero integer during a number, // such as after reading `1` or `100` but not `0`. func state1(s *scanner, c byte) int { if '0' <= c && c <= '9' { s.step = state1 return scanContinue } return state0(s, c) } // state0 is the state after reading `0` during a number. func state0(s *scanner, c byte) int { if c == '.' { s.step = stateDot return scanContinue } if c == 'e' || c == 'E' { s.step = stateE return scanContinue } return stateEndValue(s, c) } // stateDot is the state after reading the integer and decimal point in a number, // such as after reading `1.`. func stateDot(s *scanner, c byte) int { if '0' <= c && c <= '9' { s.step = stateDot0 return scanContinue } return s.error(c, "after decimal point in numeric literal") } // stateDot0 is the state after reading the integer, decimal point, and subsequent // digits of a number, such as after reading `3.14`. func stateDot0(s *scanner, c byte) int { if '0' <= c && c <= '9' { return scanContinue } if c == 'e' || c == 'E' { s.step = stateE return scanContinue } return stateEndValue(s, c) } // stateE is the state after reading the mantissa and e in a number, // such as after reading `314e` or `0.314e`. func stateE(s *scanner, c byte) int { if c == '+' || c == '-' { s.step = stateESign return scanContinue } return stateESign(s, c) } // stateESign is the state after reading the mantissa, e, and sign in a number, // such as after reading `314e-` or `0.314e+`. func stateESign(s *scanner, c byte) int { if '0' <= c && c <= '9' { s.step = stateE0 return scanContinue } return s.error(c, "in exponent of numeric literal") } // stateE0 is the state after reading the mantissa, e, optional sign, // and at least one digit of the exponent in a number, // such as after reading `314e-2` or `0.314e+1` or `3.14e0`. func stateE0(s *scanner, c byte) int { if '0' <= c && c <= '9' { return scanContinue } return stateEndValue(s, c) } // stateT is the state after reading `t`. func stateT(s *scanner, c byte) int { if c == 'r' { s.step = stateTr return scanContinue } return s.error(c, "in literal true (expecting 'r')") } // stateTr is the state after reading `tr`. func stateTr(s *scanner, c byte) int { if c == 'u' { s.step = stateTru return scanContinue } return s.error(c, "in literal true (expecting 'u')") } // stateTru is the state after reading `tru`. func stateTru(s *scanner, c byte) int { if c == 'e' { s.step = stateEndValue return scanContinue } return s.error(c, "in literal true (expecting 'e')") } // stateF is the state after reading `f`. func stateF(s *scanner, c byte) int { if c == 'a' { s.step = stateFa return scanContinue } return s.error(c, "in literal false (expecting 'a')") } // stateFa is the state after reading `fa`. func stateFa(s *scanner, c byte) int { if c == 'l' { s.step = stateFal return scanContinue } return s.error(c, "in literal false (expecting 'l')") } // stateFal is the state after reading `fal`. func stateFal(s *scanner, c byte) int { if c == 's' { s.step = stateFals return scanContinue } return s.error(c, "in literal false (expecting 's')") } // stateFals is the state after reading `fals`. func stateFals(s *scanner, c byte) int { if c == 'e' { s.step = stateEndValue return scanContinue } return s.error(c, "in literal false (expecting 'e')") } // stateN is the state after reading `n`. func stateN(s *scanner, c byte) int { if c == 'u' { s.step = stateNu return scanContinue } return s.error(c, "in literal null (expecting 'u')") } // stateNu is the state after reading `nu`. func stateNu(s *scanner, c byte) int { if c == 'l' { s.step = stateNul return scanContinue } return s.error(c, "in literal null (expecting 'l')") } // stateNul is the state after reading `nul`. func stateNul(s *scanner, c byte) int { if c == 'l' { s.step = stateEndValue return scanContinue } return s.error(c, "in literal null (expecting 'l')") } // stateError is the state after reaching a syntax error, // such as after reading `[1}` or `5.1.2`. func stateError(s *scanner, c byte) int { return scanError } // error records an error and switches to the error state. func (s *scanner) error(c byte, context string) int { s.step = stateError s.err = &SyntaxError{"invalid character " + quoteChar(c) + " " + context, s.bytes} return scanError } // quoteChar formats c as a quoted character literal. func quoteChar(c byte) string { // special cases - different from quoted strings if c == '\'' { return `'\''` } if c == '"' { return `'"'` } // use quoted string with different quotation marks s := strconv.Quote(string(c)) return "'" + s[1:len(s)-1] + "'" }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/evanphx/json-patch/v5/internal/json/decode.go
vendor/github.com/evanphx/json-patch/v5/internal/json/decode.go
// Copyright 2010 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. // Represents JSON data structure using native Go types: booleans, floats, // strings, arrays, and maps. package json import ( "encoding" "encoding/base64" "fmt" "reflect" "strconv" "strings" "sync" "unicode" "unicode/utf16" "unicode/utf8" ) // Unmarshal parses the JSON-encoded data and stores the result // in the value pointed to by v. If v is nil or not a pointer, // Unmarshal returns an InvalidUnmarshalError. // // Unmarshal uses the inverse of the encodings that // Marshal uses, allocating maps, slices, and pointers as necessary, // with the following additional rules: // // To unmarshal JSON into a pointer, Unmarshal first handles the case of // the JSON being the JSON literal null. In that case, Unmarshal sets // the pointer to nil. Otherwise, Unmarshal unmarshals the JSON into // the value pointed at by the pointer. If the pointer is nil, Unmarshal // allocates a new value for it to point to. // // To unmarshal JSON into a value implementing the Unmarshaler interface, // Unmarshal calls that value's UnmarshalJSON method, including // when the input is a JSON null. // Otherwise, if the value implements encoding.TextUnmarshaler // and the input is a JSON quoted string, Unmarshal calls that value's // UnmarshalText method with the unquoted form of the string. // // To unmarshal JSON into a struct, Unmarshal matches incoming object // keys to the keys used by Marshal (either the struct field name or its tag), // preferring an exact match but also accepting a case-insensitive match. By // default, object keys which don't have a corresponding struct field are // ignored (see Decoder.DisallowUnknownFields for an alternative). // // To unmarshal JSON into an interface value, // Unmarshal stores one of these in the interface value: // // bool, for JSON booleans // float64, for JSON numbers // string, for JSON strings // []interface{}, for JSON arrays // map[string]interface{}, for JSON objects // nil for JSON null // // To unmarshal a JSON array into a slice, Unmarshal resets the slice length // to zero and then appends each element to the slice. // As a special case, to unmarshal an empty JSON array into a slice, // Unmarshal replaces the slice with a new empty slice. // // To unmarshal a JSON array into a Go array, Unmarshal decodes // JSON array elements into corresponding Go array elements. // If the Go array is smaller than the JSON array, // the additional JSON array elements are discarded. // If the JSON array is smaller than the Go array, // the additional Go array elements are set to zero values. // // To unmarshal a JSON object into a map, Unmarshal first establishes a map to // use. If the map is nil, Unmarshal allocates a new map. Otherwise Unmarshal // reuses the existing map, keeping existing entries. Unmarshal then stores // key-value pairs from the JSON object into the map. The map's key type must // either be any string type, an integer, implement json.Unmarshaler, or // implement encoding.TextUnmarshaler. // // If the JSON-encoded data contain a syntax error, Unmarshal returns a SyntaxError. // // If a JSON value is not appropriate for a given target type, // or if a JSON number overflows the target type, Unmarshal // skips that field and completes the unmarshaling as best it can. // If no more serious errors are encountered, Unmarshal returns // an UnmarshalTypeError describing the earliest such error. In any // case, it's not guaranteed that all the remaining fields following // the problematic one will be unmarshaled into the target object. // // The JSON null value unmarshals into an interface, map, pointer, or slice // by setting that Go value to nil. Because null is often used in JSON to mean // “not present,” unmarshaling a JSON null into any other Go type has no effect // on the value and produces no error. // // When unmarshaling quoted strings, invalid UTF-8 or // invalid UTF-16 surrogate pairs are not treated as an error. // Instead, they are replaced by the Unicode replacement // character U+FFFD. func Unmarshal(data []byte, v any) error { // Check for well-formedness. // Avoids filling out half a data structure // before discovering a JSON syntax error. d := ds.Get().(*decodeState) defer ds.Put(d) //var d decodeState d.useNumber = true err := checkValid(data, &d.scan) if err != nil { return err } d.init(data) return d.unmarshal(v) } var ds = sync.Pool{ New: func() any { return new(decodeState) }, } func UnmarshalWithKeys(data []byte, v any) ([]string, error) { // Check for well-formedness. // Avoids filling out half a data structure // before discovering a JSON syntax error. d := ds.Get().(*decodeState) defer ds.Put(d) //var d decodeState d.useNumber = true err := checkValid(data, &d.scan) if err != nil { return nil, err } d.init(data) err = d.unmarshal(v) if err != nil { return nil, err } return d.lastKeys, nil } func UnmarshalValid(data []byte, v any) error { // Check for well-formedness. // Avoids filling out half a data structure // before discovering a JSON syntax error. d := ds.Get().(*decodeState) defer ds.Put(d) //var d decodeState d.useNumber = true d.init(data) return d.unmarshal(v) } func UnmarshalValidWithKeys(data []byte, v any) ([]string, error) { // Check for well-formedness. // Avoids filling out half a data structure // before discovering a JSON syntax error. d := ds.Get().(*decodeState) defer ds.Put(d) //var d decodeState d.useNumber = true d.init(data) err := d.unmarshal(v) if err != nil { return nil, err } return d.lastKeys, nil } // Unmarshaler is the interface implemented by types // that can unmarshal a JSON description of themselves. // The input can be assumed to be a valid encoding of // a JSON value. UnmarshalJSON must copy the JSON data // if it wishes to retain the data after returning. // // By convention, to approximate the behavior of Unmarshal itself, // Unmarshalers implement UnmarshalJSON([]byte("null")) as a no-op. type Unmarshaler interface { UnmarshalJSON([]byte) error } // An UnmarshalTypeError describes a JSON value that was // not appropriate for a value of a specific Go type. type UnmarshalTypeError struct { Value string // description of JSON value - "bool", "array", "number -5" Type reflect.Type // type of Go value it could not be assigned to Offset int64 // error occurred after reading Offset bytes Struct string // name of the struct type containing the field Field string // the full path from root node to the field } func (e *UnmarshalTypeError) Error() string { if e.Struct != "" || e.Field != "" { return "json: cannot unmarshal " + e.Value + " into Go struct field " + e.Struct + "." + e.Field + " of type " + e.Type.String() } return "json: cannot unmarshal " + e.Value + " into Go value of type " + e.Type.String() } // An UnmarshalFieldError describes a JSON object key that // led to an unexported (and therefore unwritable) struct field. // // Deprecated: No longer used; kept for compatibility. type UnmarshalFieldError struct { Key string Type reflect.Type Field reflect.StructField } func (e *UnmarshalFieldError) Error() string { return "json: cannot unmarshal object key " + strconv.Quote(e.Key) + " into unexported field " + e.Field.Name + " of type " + e.Type.String() } // An InvalidUnmarshalError describes an invalid argument passed to Unmarshal. // (The argument to Unmarshal must be a non-nil pointer.) type InvalidUnmarshalError struct { Type reflect.Type } func (e *InvalidUnmarshalError) Error() string { if e.Type == nil { return "json: Unmarshal(nil)" } if e.Type.Kind() != reflect.Pointer { return "json: Unmarshal(non-pointer " + e.Type.String() + ")" } return "json: Unmarshal(nil " + e.Type.String() + ")" } func (d *decodeState) unmarshal(v any) error { rv := reflect.ValueOf(v) if rv.Kind() != reflect.Pointer || rv.IsNil() { return &InvalidUnmarshalError{reflect.TypeOf(v)} } d.scan.reset() d.scanWhile(scanSkipSpace) // We decode rv not rv.Elem because the Unmarshaler interface // test must be applied at the top level of the value. err := d.value(rv) if err != nil { return d.addErrorContext(err) } return d.savedError } // A Number represents a JSON number literal. type Number string // String returns the literal text of the number. func (n Number) String() string { return string(n) } // Float64 returns the number as a float64. func (n Number) Float64() (float64, error) { return strconv.ParseFloat(string(n), 64) } // Int64 returns the number as an int64. func (n Number) Int64() (int64, error) { return strconv.ParseInt(string(n), 10, 64) } // An errorContext provides context for type errors during decoding. type errorContext struct { Struct reflect.Type FieldStack []string } // decodeState represents the state while decoding a JSON value. type decodeState struct { data []byte off int // next read offset in data opcode int // last read result scan scanner errorContext *errorContext savedError error useNumber bool disallowUnknownFields bool lastKeys []string } // readIndex returns the position of the last byte read. func (d *decodeState) readIndex() int { return d.off - 1 } // phasePanicMsg is used as a panic message when we end up with something that // shouldn't happen. It can indicate a bug in the JSON decoder, or that // something is editing the data slice while the decoder executes. const phasePanicMsg = "JSON decoder out of sync - data changing underfoot?" func (d *decodeState) init(data []byte) *decodeState { d.data = data d.off = 0 d.savedError = nil if d.errorContext != nil { d.errorContext.Struct = nil // Reuse the allocated space for the FieldStack slice. d.errorContext.FieldStack = d.errorContext.FieldStack[:0] } return d } // saveError saves the first err it is called with, // for reporting at the end of the unmarshal. func (d *decodeState) saveError(err error) { if d.savedError == nil { d.savedError = d.addErrorContext(err) } } // addErrorContext returns a new error enhanced with information from d.errorContext func (d *decodeState) addErrorContext(err error) error { if d.errorContext != nil && (d.errorContext.Struct != nil || len(d.errorContext.FieldStack) > 0) { switch err := err.(type) { case *UnmarshalTypeError: err.Struct = d.errorContext.Struct.Name() err.Field = strings.Join(d.errorContext.FieldStack, ".") } } return err } // skip scans to the end of what was started. func (d *decodeState) skip() { s, data, i := &d.scan, d.data, d.off depth := len(s.parseState) for { op := s.step(s, data[i]) i++ if len(s.parseState) < depth { d.off = i d.opcode = op return } } } // scanNext processes the byte at d.data[d.off]. func (d *decodeState) scanNext() { if d.off < len(d.data) { d.opcode = d.scan.step(&d.scan, d.data[d.off]) d.off++ } else { d.opcode = d.scan.eof() d.off = len(d.data) + 1 // mark processed EOF with len+1 } } // scanWhile processes bytes in d.data[d.off:] until it // receives a scan code not equal to op. func (d *decodeState) scanWhile(op int) { s, data, i := &d.scan, d.data, d.off for i < len(data) { newOp := s.step(s, data[i]) i++ if newOp != op { d.opcode = newOp d.off = i return } } d.off = len(data) + 1 // mark processed EOF with len+1 d.opcode = d.scan.eof() } // rescanLiteral is similar to scanWhile(scanContinue), but it specialises the // common case where we're decoding a literal. The decoder scans the input // twice, once for syntax errors and to check the length of the value, and the // second to perform the decoding. // // Only in the second step do we use decodeState to tokenize literals, so we // know there aren't any syntax errors. We can take advantage of that knowledge, // and scan a literal's bytes much more quickly. func (d *decodeState) rescanLiteral() { data, i := d.data, d.off Switch: switch data[i-1] { case '"': // string for ; i < len(data); i++ { switch data[i] { case '\\': i++ // escaped char case '"': i++ // tokenize the closing quote too break Switch } } case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-': // number for ; i < len(data); i++ { switch data[i] { case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', 'e', 'E', '+', '-': default: break Switch } } case 't': // true i += len("rue") case 'f': // false i += len("alse") case 'n': // null i += len("ull") } if i < len(data) { d.opcode = stateEndValue(&d.scan, data[i]) } else { d.opcode = scanEnd } d.off = i + 1 } // value consumes a JSON value from d.data[d.off-1:], decoding into v, and // reads the following byte ahead. If v is invalid, the value is discarded. // The first byte of the value has been read already. func (d *decodeState) value(v reflect.Value) error { switch d.opcode { default: panic(phasePanicMsg) case scanBeginArray: if v.IsValid() { if err := d.array(v); err != nil { return err } } else { d.skip() } d.scanNext() case scanBeginObject: if v.IsValid() { if err := d.object(v); err != nil { return err } } else { d.skip() } d.scanNext() case scanBeginLiteral: // All bytes inside literal return scanContinue op code. start := d.readIndex() d.rescanLiteral() if v.IsValid() { if err := d.literalStore(d.data[start:d.readIndex()], v, false); err != nil { return err } } } return nil } type unquotedValue struct{} // valueQuoted is like value but decodes a // quoted string literal or literal null into an interface value. // If it finds anything other than a quoted string literal or null, // valueQuoted returns unquotedValue{}. func (d *decodeState) valueQuoted() any { switch d.opcode { default: panic(phasePanicMsg) case scanBeginArray, scanBeginObject: d.skip() d.scanNext() case scanBeginLiteral: v := d.literalInterface() switch v.(type) { case nil, string: return v } } return unquotedValue{} } // indirect walks down v allocating pointers as needed, // until it gets to a non-pointer. // If it encounters an Unmarshaler, indirect stops and returns that. // If decodingNull is true, indirect stops at the first settable pointer so it // can be set to nil. func indirect(v reflect.Value, decodingNull bool) (Unmarshaler, encoding.TextUnmarshaler, reflect.Value) { // Issue #24153 indicates that it is generally not a guaranteed property // that you may round-trip a reflect.Value by calling Value.Addr().Elem() // and expect the value to still be settable for values derived from // unexported embedded struct fields. // // The logic below effectively does this when it first addresses the value // (to satisfy possible pointer methods) and continues to dereference // subsequent pointers as necessary. // // After the first round-trip, we set v back to the original value to // preserve the original RW flags contained in reflect.Value. v0 := v haveAddr := false // If v is a named type and is addressable, // start with its address, so that if the type has pointer methods, // we find them. if v.Kind() != reflect.Pointer && v.Type().Name() != "" && v.CanAddr() { haveAddr = true v = v.Addr() } for { // Load value from interface, but only if the result will be // usefully addressable. if v.Kind() == reflect.Interface && !v.IsNil() { e := v.Elem() if e.Kind() == reflect.Pointer && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Pointer) { haveAddr = false v = e continue } } if v.Kind() != reflect.Pointer { break } if decodingNull && v.CanSet() { break } // Prevent infinite loop if v is an interface pointing to its own address: // var v interface{} // v = &v if v.Elem().Kind() == reflect.Interface && v.Elem().Elem() == v { v = v.Elem() break } if v.IsNil() { v.Set(reflect.New(v.Type().Elem())) } if v.Type().NumMethod() > 0 && v.CanInterface() { if u, ok := v.Interface().(Unmarshaler); ok { return u, nil, reflect.Value{} } if !decodingNull { if u, ok := v.Interface().(encoding.TextUnmarshaler); ok { return nil, u, reflect.Value{} } } } if haveAddr { v = v0 // restore original value after round-trip Value.Addr().Elem() haveAddr = false } else { v = v.Elem() } } return nil, nil, v } // array consumes an array from d.data[d.off-1:], decoding into v. // The first byte of the array ('[') has been read already. func (d *decodeState) array(v reflect.Value) error { // Check for unmarshaler. u, ut, pv := indirect(v, false) if u != nil { start := d.readIndex() d.skip() return u.UnmarshalJSON(d.data[start:d.off]) } if ut != nil { d.saveError(&UnmarshalTypeError{Value: "array", Type: v.Type(), Offset: int64(d.off)}) d.skip() return nil } v = pv // Check type of target. switch v.Kind() { case reflect.Interface: if v.NumMethod() == 0 { // Decoding into nil interface? Switch to non-reflect code. ai := d.arrayInterface() v.Set(reflect.ValueOf(ai)) return nil } // Otherwise it's invalid. fallthrough default: d.saveError(&UnmarshalTypeError{Value: "array", Type: v.Type(), Offset: int64(d.off)}) d.skip() return nil case reflect.Array, reflect.Slice: break } i := 0 for { // Look ahead for ] - can only happen on first iteration. d.scanWhile(scanSkipSpace) if d.opcode == scanEndArray { break } // Get element of array, growing if necessary. if v.Kind() == reflect.Slice { // Grow slice if necessary if i >= v.Cap() { newcap := v.Cap() + v.Cap()/2 if newcap < 4 { newcap = 4 } newv := reflect.MakeSlice(v.Type(), v.Len(), newcap) reflect.Copy(newv, v) v.Set(newv) } if i >= v.Len() { v.SetLen(i + 1) } } if i < v.Len() { // Decode into element. if err := d.value(v.Index(i)); err != nil { return err } } else { // Ran out of fixed array: skip. if err := d.value(reflect.Value{}); err != nil { return err } } i++ // Next token must be , or ]. if d.opcode == scanSkipSpace { d.scanWhile(scanSkipSpace) } if d.opcode == scanEndArray { break } if d.opcode != scanArrayValue { panic(phasePanicMsg) } } if i < v.Len() { if v.Kind() == reflect.Array { // Array. Zero the rest. z := reflect.Zero(v.Type().Elem()) for ; i < v.Len(); i++ { v.Index(i).Set(z) } } else { v.SetLen(i) } } if i == 0 && v.Kind() == reflect.Slice { v.Set(reflect.MakeSlice(v.Type(), 0, 0)) } return nil } var nullLiteral = []byte("null") var textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() // object consumes an object from d.data[d.off-1:], decoding into v. // The first byte ('{') of the object has been read already. func (d *decodeState) object(v reflect.Value) error { // Check for unmarshaler. u, ut, pv := indirect(v, false) if u != nil { start := d.readIndex() d.skip() return u.UnmarshalJSON(d.data[start:d.off]) } if ut != nil { d.saveError(&UnmarshalTypeError{Value: "object", Type: v.Type(), Offset: int64(d.off)}) d.skip() return nil } v = pv t := v.Type() // Decoding into nil interface? Switch to non-reflect code. if v.Kind() == reflect.Interface && v.NumMethod() == 0 { oi := d.objectInterface() v.Set(reflect.ValueOf(oi)) return nil } var fields structFields // Check type of target: // struct or // map[T1]T2 where T1 is string, an integer type, // or an encoding.TextUnmarshaler switch v.Kind() { case reflect.Map: // Map key must either have string kind, have an integer kind, // or be an encoding.TextUnmarshaler. switch t.Key().Kind() { case reflect.String, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: default: if !reflect.PointerTo(t.Key()).Implements(textUnmarshalerType) { d.saveError(&UnmarshalTypeError{Value: "object", Type: t, Offset: int64(d.off)}) d.skip() return nil } } if v.IsNil() { v.Set(reflect.MakeMap(t)) } case reflect.Struct: fields = cachedTypeFields(t) // ok default: d.saveError(&UnmarshalTypeError{Value: "object", Type: t, Offset: int64(d.off)}) d.skip() return nil } var mapElem reflect.Value var origErrorContext errorContext if d.errorContext != nil { origErrorContext = *d.errorContext } var keys []string for { // Read opening " of string key or closing }. d.scanWhile(scanSkipSpace) if d.opcode == scanEndObject { // closing } - can only happen on first iteration. break } if d.opcode != scanBeginLiteral { panic(phasePanicMsg) } // Read key. start := d.readIndex() d.rescanLiteral() item := d.data[start:d.readIndex()] key, ok := unquoteBytes(item) if !ok { panic(phasePanicMsg) } keys = append(keys, string(key)) // Figure out field corresponding to key. var subv reflect.Value destring := false // whether the value is wrapped in a string to be decoded first if v.Kind() == reflect.Map { elemType := t.Elem() if !mapElem.IsValid() { mapElem = reflect.New(elemType).Elem() } else { mapElem.Set(reflect.Zero(elemType)) } subv = mapElem } else { var f *field if i, ok := fields.nameIndex[string(key)]; ok { // Found an exact name match. f = &fields.list[i] } else { // Fall back to the expensive case-insensitive // linear search. for i := range fields.list { ff := &fields.list[i] if ff.equalFold(ff.nameBytes, key) { f = ff break } } } if f != nil { subv = v destring = f.quoted for _, i := range f.index { if subv.Kind() == reflect.Pointer { if subv.IsNil() { // If a struct embeds a pointer to an unexported type, // it is not possible to set a newly allocated value // since the field is unexported. // // See https://golang.org/issue/21357 if !subv.CanSet() { d.saveError(fmt.Errorf("json: cannot set embedded pointer to unexported struct: %v", subv.Type().Elem())) // Invalidate subv to ensure d.value(subv) skips over // the JSON value without assigning it to subv. subv = reflect.Value{} destring = false break } subv.Set(reflect.New(subv.Type().Elem())) } subv = subv.Elem() } subv = subv.Field(i) } if d.errorContext == nil { d.errorContext = new(errorContext) } d.errorContext.FieldStack = append(d.errorContext.FieldStack, f.name) d.errorContext.Struct = t } else if d.disallowUnknownFields { d.saveError(fmt.Errorf("json: unknown field %q", key)) } } // Read : before value. if d.opcode == scanSkipSpace { d.scanWhile(scanSkipSpace) } if d.opcode != scanObjectKey { panic(phasePanicMsg) } d.scanWhile(scanSkipSpace) if destring { switch qv := d.valueQuoted().(type) { case nil: if err := d.literalStore(nullLiteral, subv, false); err != nil { return err } case string: if err := d.literalStore([]byte(qv), subv, true); err != nil { return err } default: d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal unquoted value into %v", subv.Type())) } } else { if err := d.value(subv); err != nil { return err } } // Write value back to map; // if using struct, subv points into struct already. if v.Kind() == reflect.Map { kt := t.Key() var kv reflect.Value switch { case reflect.PointerTo(kt).Implements(textUnmarshalerType): kv = reflect.New(kt) if err := d.literalStore(item, kv, true); err != nil { return err } kv = kv.Elem() case kt.Kind() == reflect.String: kv = reflect.ValueOf(key).Convert(kt) default: switch kt.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: s := string(key) n, err := strconv.ParseInt(s, 10, 64) if err != nil || reflect.Zero(kt).OverflowInt(n) { d.saveError(&UnmarshalTypeError{Value: "number " + s, Type: kt, Offset: int64(start + 1)}) break } kv = reflect.ValueOf(n).Convert(kt) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: s := string(key) n, err := strconv.ParseUint(s, 10, 64) if err != nil || reflect.Zero(kt).OverflowUint(n) { d.saveError(&UnmarshalTypeError{Value: "number " + s, Type: kt, Offset: int64(start + 1)}) break } kv = reflect.ValueOf(n).Convert(kt) default: panic("json: Unexpected key type") // should never occur } } if kv.IsValid() { v.SetMapIndex(kv, subv) } } // Next token must be , or }. if d.opcode == scanSkipSpace { d.scanWhile(scanSkipSpace) } if d.errorContext != nil { // Reset errorContext to its original state. // Keep the same underlying array for FieldStack, to reuse the // space and avoid unnecessary allocs. d.errorContext.FieldStack = d.errorContext.FieldStack[:len(origErrorContext.FieldStack)] d.errorContext.Struct = origErrorContext.Struct } if d.opcode == scanEndObject { break } if d.opcode != scanObjectValue { panic(phasePanicMsg) } } if v.Kind() == reflect.Map { d.lastKeys = keys } return nil } // convertNumber converts the number literal s to a float64 or a Number // depending on the setting of d.useNumber. func (d *decodeState) convertNumber(s string) (any, error) { if d.useNumber { return Number(s), nil } f, err := strconv.ParseFloat(s, 64) if err != nil { return nil, &UnmarshalTypeError{Value: "number " + s, Type: reflect.TypeOf(0.0), Offset: int64(d.off)} } return f, nil } var numberType = reflect.TypeOf(Number("")) // literalStore decodes a literal stored in item into v. // // fromQuoted indicates whether this literal came from unwrapping a // string from the ",string" struct tag option. this is used only to // produce more helpful error messages. func (d *decodeState) literalStore(item []byte, v reflect.Value, fromQuoted bool) error { // Check for unmarshaler. if len(item) == 0 { //Empty string given d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) return nil } isNull := item[0] == 'n' // null u, ut, pv := indirect(v, isNull) if u != nil { return u.UnmarshalJSON(item) } if ut != nil { if item[0] != '"' { if fromQuoted { d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) return nil } val := "number" switch item[0] { case 'n': val = "null" case 't', 'f': val = "bool" } d.saveError(&UnmarshalTypeError{Value: val, Type: v.Type(), Offset: int64(d.readIndex())}) return nil } s, ok := unquoteBytes(item) if !ok { if fromQuoted { return fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()) } panic(phasePanicMsg) } return ut.UnmarshalText(s) } v = pv switch c := item[0]; c { case 'n': // null // The main parser checks that only true and false can reach here, // but if this was a quoted string input, it could be anything. if fromQuoted && string(item) != "null" { d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) break } switch v.Kind() { case reflect.Interface, reflect.Pointer, reflect.Map, reflect.Slice: v.Set(reflect.Zero(v.Type())) // otherwise, ignore null for primitives/string } case 't', 'f': // true, false value := item[0] == 't' // The main parser checks that only true and false can reach here, // but if this was a quoted string input, it could be anything. if fromQuoted && string(item) != "true" && string(item) != "false" { d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) break } switch v.Kind() { default: if fromQuoted { d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) } else { d.saveError(&UnmarshalTypeError{Value: "bool", Type: v.Type(), Offset: int64(d.readIndex())}) } case reflect.Bool: v.SetBool(value) case reflect.Interface: if v.NumMethod() == 0 { v.Set(reflect.ValueOf(value)) } else { d.saveError(&UnmarshalTypeError{Value: "bool", Type: v.Type(), Offset: int64(d.readIndex())}) } } case '"': // string s, ok := unquoteBytes(item) if !ok { if fromQuoted { return fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()) } panic(phasePanicMsg) } switch v.Kind() { default: d.saveError(&UnmarshalTypeError{Value: "string", Type: v.Type(), Offset: int64(d.readIndex())}) case reflect.Slice: if v.Type().Elem().Kind() != reflect.Uint8 { d.saveError(&UnmarshalTypeError{Value: "string", Type: v.Type(), Offset: int64(d.readIndex())}) break } b := make([]byte, base64.StdEncoding.DecodedLen(len(s))) n, err := base64.StdEncoding.Decode(b, s) if err != nil { d.saveError(err) break } v.SetBytes(b[:n]) case reflect.String: if v.Type() == numberType && !isValidNumber(string(s)) { return fmt.Errorf("json: invalid number literal, trying to unmarshal %q into Number", item) } v.SetString(string(s)) case reflect.Interface: if v.NumMethod() == 0 { v.Set(reflect.ValueOf(string(s))) } else { d.saveError(&UnmarshalTypeError{Value: "string", Type: v.Type(), Offset: int64(d.readIndex())}) } } default: // number if c != '-' && (c < '0' || c > '9') { if fromQuoted { return fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()) } panic(phasePanicMsg) } s := string(item) switch v.Kind() { default: if v.Kind() == reflect.String && v.Type() == numberType { // s must be a valid number, because it's // already been tokenized. v.SetString(s) break } if fromQuoted { return fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()) } d.saveError(&UnmarshalTypeError{Value: "number", Type: v.Type(), Offset: int64(d.readIndex())}) case reflect.Interface: n, err := d.convertNumber(s) if err != nil { d.saveError(err) break } if v.NumMethod() != 0 { d.saveError(&UnmarshalTypeError{Value: "number", Type: v.Type(), Offset: int64(d.readIndex())}) break } v.Set(reflect.ValueOf(n)) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: n, err := strconv.ParseInt(s, 10, 64) if err != nil || v.OverflowInt(n) { d.saveError(&UnmarshalTypeError{Value: "number " + s, Type: v.Type(), Offset: int64(d.readIndex())}) break } v.SetInt(n) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: n, err := strconv.ParseUint(s, 10, 64) if err != nil || v.OverflowUint(n) { d.saveError(&UnmarshalTypeError{Value: "number " + s, Type: v.Type(), Offset: int64(d.readIndex())}) break } v.SetUint(n) case reflect.Float32, reflect.Float64: n, err := strconv.ParseFloat(s, v.Type().Bits()) if err != nil || v.OverflowFloat(n) { d.saveError(&UnmarshalTypeError{Value: "number " + s, Type: v.Type(), Offset: int64(d.readIndex())}) break } v.SetFloat(n) } } return nil } // The xxxInterface routines build up a value to be stored // in an empty interface. They are not strictly necessary, // but they avoid the weight of reflection in this common case. // valueInterface is like value but returns interface{} func (d *decodeState) valueInterface() (val any) { switch d.opcode { default: panic(phasePanicMsg) case scanBeginArray: val = d.arrayInterface() d.scanNext() case scanBeginObject: val = d.objectInterface() d.scanNext() case scanBeginLiteral: val = d.literalInterface() } return } // arrayInterface is like array but returns []interface{}. func (d *decodeState) arrayInterface() []any { var v = make([]any, 0) for { // Look ahead for ] - can only happen on first iteration. d.scanWhile(scanSkipSpace) if d.opcode == scanEndArray {
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gogo/protobuf/proto/deprecated.go
vendor/github.com/gogo/protobuf/proto/deprecated.go
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2018 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // 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. package proto import "errors" // Deprecated: do not use. type Stats struct{ Emalloc, Dmalloc, Encode, Decode, Chit, Cmiss, Size uint64 } // Deprecated: do not use. func GetStats() Stats { return Stats{} } // Deprecated: do not use. func MarshalMessageSet(interface{}) ([]byte, error) { return nil, errors.New("proto: not implemented") } // Deprecated: do not use. func UnmarshalMessageSet([]byte, interface{}) error { return errors.New("proto: not implemented") } // Deprecated: do not use. func MarshalMessageSetJSON(interface{}) ([]byte, error) { return nil, errors.New("proto: not implemented") } // Deprecated: do not use. func UnmarshalMessageSetJSON([]byte, interface{}) error { return errors.New("proto: not implemented") } // Deprecated: do not use. func RegisterMessageSetType(Message, int32, string) {}
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gogo/protobuf/proto/text.go
vendor/github.com/gogo/protobuf/proto/text.go
// Protocol Buffers for Go with Gadgets // // Copyright (c) 2013, The GoGo Authors. All rights reserved. // http://github.com/gogo/protobuf // // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // 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. package proto // Functions for writing the text protocol buffer format. import ( "bufio" "bytes" "encoding" "errors" "fmt" "io" "log" "math" "reflect" "sort" "strings" "sync" "time" ) var ( newline = []byte("\n") spaces = []byte(" ") endBraceNewline = []byte("}\n") backslashN = []byte{'\\', 'n'} backslashR = []byte{'\\', 'r'} backslashT = []byte{'\\', 't'} backslashDQ = []byte{'\\', '"'} backslashBS = []byte{'\\', '\\'} posInf = []byte("inf") negInf = []byte("-inf") nan = []byte("nan") ) type writer interface { io.Writer WriteByte(byte) error } // textWriter is an io.Writer that tracks its indentation level. type textWriter struct { ind int complete bool // if the current position is a complete line compact bool // whether to write out as a one-liner w writer } func (w *textWriter) WriteString(s string) (n int, err error) { if !strings.Contains(s, "\n") { if !w.compact && w.complete { w.writeIndent() } w.complete = false return io.WriteString(w.w, s) } // WriteString is typically called without newlines, so this // codepath and its copy are rare. We copy to avoid // duplicating all of Write's logic here. return w.Write([]byte(s)) } func (w *textWriter) Write(p []byte) (n int, err error) { newlines := bytes.Count(p, newline) if newlines == 0 { if !w.compact && w.complete { w.writeIndent() } n, err = w.w.Write(p) w.complete = false return n, err } frags := bytes.SplitN(p, newline, newlines+1) if w.compact { for i, frag := range frags { if i > 0 { if err := w.w.WriteByte(' '); err != nil { return n, err } n++ } nn, err := w.w.Write(frag) n += nn if err != nil { return n, err } } return n, nil } for i, frag := range frags { if w.complete { w.writeIndent() } nn, err := w.w.Write(frag) n += nn if err != nil { return n, err } if i+1 < len(frags) { if err := w.w.WriteByte('\n'); err != nil { return n, err } n++ } } w.complete = len(frags[len(frags)-1]) == 0 return n, nil } func (w *textWriter) WriteByte(c byte) error { if w.compact && c == '\n' { c = ' ' } if !w.compact && w.complete { w.writeIndent() } err := w.w.WriteByte(c) w.complete = c == '\n' return err } func (w *textWriter) indent() { w.ind++ } func (w *textWriter) unindent() { if w.ind == 0 { log.Print("proto: textWriter unindented too far") return } w.ind-- } func writeName(w *textWriter, props *Properties) error { if _, err := w.WriteString(props.OrigName); err != nil { return err } if props.Wire != "group" { return w.WriteByte(':') } return nil } func requiresQuotes(u string) bool { // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted. for _, ch := range u { switch { case ch == '.' || ch == '/' || ch == '_': continue case '0' <= ch && ch <= '9': continue case 'A' <= ch && ch <= 'Z': continue case 'a' <= ch && ch <= 'z': continue default: return true } } return false } // isAny reports whether sv is a google.protobuf.Any message func isAny(sv reflect.Value) bool { type wkt interface { XXX_WellKnownType() string } t, ok := sv.Addr().Interface().(wkt) return ok && t.XXX_WellKnownType() == "Any" } // writeProto3Any writes an expanded google.protobuf.Any message. // // It returns (false, nil) if sv value can't be unmarshaled (e.g. because // required messages are not linked in). // // It returns (true, error) when sv was written in expanded format or an error // was encountered. func (tm *TextMarshaler) writeProto3Any(w *textWriter, sv reflect.Value) (bool, error) { turl := sv.FieldByName("TypeUrl") val := sv.FieldByName("Value") if !turl.IsValid() || !val.IsValid() { return true, errors.New("proto: invalid google.protobuf.Any message") } b, ok := val.Interface().([]byte) if !ok { return true, errors.New("proto: invalid google.protobuf.Any message") } parts := strings.Split(turl.String(), "/") mt := MessageType(parts[len(parts)-1]) if mt == nil { return false, nil } m := reflect.New(mt.Elem()) if err := Unmarshal(b, m.Interface().(Message)); err != nil { return false, nil } w.Write([]byte("[")) u := turl.String() if requiresQuotes(u) { writeString(w, u) } else { w.Write([]byte(u)) } if w.compact { w.Write([]byte("]:<")) } else { w.Write([]byte("]: <\n")) w.ind++ } if err := tm.writeStruct(w, m.Elem()); err != nil { return true, err } if w.compact { w.Write([]byte("> ")) } else { w.ind-- w.Write([]byte(">\n")) } return true, nil } func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error { if tm.ExpandAny && isAny(sv) { if canExpand, err := tm.writeProto3Any(w, sv); canExpand { return err } } st := sv.Type() sprops := GetProperties(st) for i := 0; i < sv.NumField(); i++ { fv := sv.Field(i) props := sprops.Prop[i] name := st.Field(i).Name if name == "XXX_NoUnkeyedLiteral" { continue } if strings.HasPrefix(name, "XXX_") { // There are two XXX_ fields: // XXX_unrecognized []byte // XXX_extensions map[int32]proto.Extension // The first is handled here; // the second is handled at the bottom of this function. if name == "XXX_unrecognized" && !fv.IsNil() { if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil { return err } } continue } if fv.Kind() == reflect.Ptr && fv.IsNil() { // Field not filled in. This could be an optional field or // a required field that wasn't filled in. Either way, there // isn't anything we can show for it. continue } if fv.Kind() == reflect.Slice && fv.IsNil() { // Repeated field that is empty, or a bytes field that is unused. continue } if props.Repeated && fv.Kind() == reflect.Slice { // Repeated field. for j := 0; j < fv.Len(); j++ { if err := writeName(w, props); err != nil { return err } if !w.compact { if err := w.WriteByte(' '); err != nil { return err } } v := fv.Index(j) if v.Kind() == reflect.Ptr && v.IsNil() { // A nil message in a repeated field is not valid, // but we can handle that more gracefully than panicking. if _, err := w.Write([]byte("<nil>\n")); err != nil { return err } continue } if len(props.Enum) > 0 { if err := tm.writeEnum(w, v, props); err != nil { return err } } else if err := tm.writeAny(w, v, props); err != nil { return err } if err := w.WriteByte('\n'); err != nil { return err } } continue } if fv.Kind() == reflect.Map { // Map fields are rendered as a repeated struct with key/value fields. keys := fv.MapKeys() sort.Sort(mapKeys(keys)) for _, key := range keys { val := fv.MapIndex(key) if err := writeName(w, props); err != nil { return err } if !w.compact { if err := w.WriteByte(' '); err != nil { return err } } // open struct if err := w.WriteByte('<'); err != nil { return err } if !w.compact { if err := w.WriteByte('\n'); err != nil { return err } } w.indent() // key if _, err := w.WriteString("key:"); err != nil { return err } if !w.compact { if err := w.WriteByte(' '); err != nil { return err } } if err := tm.writeAny(w, key, props.MapKeyProp); err != nil { return err } if err := w.WriteByte('\n'); err != nil { return err } // nil values aren't legal, but we can avoid panicking because of them. if val.Kind() != reflect.Ptr || !val.IsNil() { // value if _, err := w.WriteString("value:"); err != nil { return err } if !w.compact { if err := w.WriteByte(' '); err != nil { return err } } if err := tm.writeAny(w, val, props.MapValProp); err != nil { return err } if err := w.WriteByte('\n'); err != nil { return err } } // close struct w.unindent() if err := w.WriteByte('>'); err != nil { return err } if err := w.WriteByte('\n'); err != nil { return err } } continue } if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 { // empty bytes field continue } if props.proto3 && fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice { // proto3 non-repeated scalar field; skip if zero value if isProto3Zero(fv) { continue } } if fv.Kind() == reflect.Interface { // Check if it is a oneof. if st.Field(i).Tag.Get("protobuf_oneof") != "" { // fv is nil, or holds a pointer to generated struct. // That generated struct has exactly one field, // which has a protobuf struct tag. if fv.IsNil() { continue } inner := fv.Elem().Elem() // interface -> *T -> T tag := inner.Type().Field(0).Tag.Get("protobuf") props = new(Properties) // Overwrite the outer props var, but not its pointee. props.Parse(tag) // Write the value in the oneof, not the oneof itself. fv = inner.Field(0) // Special case to cope with malformed messages gracefully: // If the value in the oneof is a nil pointer, don't panic // in writeAny. if fv.Kind() == reflect.Ptr && fv.IsNil() { // Use errors.New so writeAny won't render quotes. msg := errors.New("/* nil */") fv = reflect.ValueOf(&msg).Elem() } } } if err := writeName(w, props); err != nil { return err } if !w.compact { if err := w.WriteByte(' '); err != nil { return err } } if len(props.Enum) > 0 { if err := tm.writeEnum(w, fv, props); err != nil { return err } } else if err := tm.writeAny(w, fv, props); err != nil { return err } if err := w.WriteByte('\n'); err != nil { return err } } // Extensions (the XXX_extensions field). pv := sv if pv.CanAddr() { pv = sv.Addr() } else { pv = reflect.New(sv.Type()) pv.Elem().Set(sv) } if _, err := extendable(pv.Interface()); err == nil { if err := tm.writeExtensions(w, pv); err != nil { return err } } return nil } var textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() // writeAny writes an arbitrary field. func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error { v = reflect.Indirect(v) if props != nil { if len(props.CustomType) > 0 { custom, ok := v.Interface().(Marshaler) if ok { data, err := custom.Marshal() if err != nil { return err } if err := writeString(w, string(data)); err != nil { return err } return nil } } else if len(props.CastType) > 0 { if _, ok := v.Interface().(interface { String() string }); ok { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: _, err := fmt.Fprintf(w, "%d", v.Interface()) return err } } } else if props.StdTime { t, ok := v.Interface().(time.Time) if !ok { return fmt.Errorf("stdtime is not time.Time, but %T", v.Interface()) } tproto, err := timestampProto(t) if err != nil { return err } propsCopy := *props // Make a copy so that this is goroutine-safe propsCopy.StdTime = false err = tm.writeAny(w, reflect.ValueOf(tproto), &propsCopy) return err } else if props.StdDuration { d, ok := v.Interface().(time.Duration) if !ok { return fmt.Errorf("stdtime is not time.Duration, but %T", v.Interface()) } dproto := durationProto(d) propsCopy := *props // Make a copy so that this is goroutine-safe propsCopy.StdDuration = false err := tm.writeAny(w, reflect.ValueOf(dproto), &propsCopy) return err } } // Floats have special cases. if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 { x := v.Float() var b []byte switch { case math.IsInf(x, 1): b = posInf case math.IsInf(x, -1): b = negInf case math.IsNaN(x): b = nan } if b != nil { _, err := w.Write(b) return err } // Other values are handled below. } // We don't attempt to serialise every possible value type; only those // that can occur in protocol buffers. switch v.Kind() { case reflect.Slice: // Should only be a []byte; repeated fields are handled in writeStruct. if err := writeString(w, string(v.Bytes())); err != nil { return err } case reflect.String: if err := writeString(w, v.String()); err != nil { return err } case reflect.Struct: // Required/optional group/message. var bra, ket byte = '<', '>' if props != nil && props.Wire == "group" { bra, ket = '{', '}' } if err := w.WriteByte(bra); err != nil { return err } if !w.compact { if err := w.WriteByte('\n'); err != nil { return err } } w.indent() if v.CanAddr() { // Calling v.Interface on a struct causes the reflect package to // copy the entire struct. This is racy with the new Marshaler // since we atomically update the XXX_sizecache. // // Thus, we retrieve a pointer to the struct if possible to avoid // a race since v.Interface on the pointer doesn't copy the struct. // // If v is not addressable, then we are not worried about a race // since it implies that the binary Marshaler cannot possibly be // mutating this value. v = v.Addr() } if v.Type().Implements(textMarshalerType) { text, err := v.Interface().(encoding.TextMarshaler).MarshalText() if err != nil { return err } if _, err = w.Write(text); err != nil { return err } } else { if v.Kind() == reflect.Ptr { v = v.Elem() } if err := tm.writeStruct(w, v); err != nil { return err } } w.unindent() if err := w.WriteByte(ket); err != nil { return err } default: _, err := fmt.Fprint(w, v.Interface()) return err } return nil } // equivalent to C's isprint. func isprint(c byte) bool { return c >= 0x20 && c < 0x7f } // writeString writes a string in the protocol buffer text format. // It is similar to strconv.Quote except we don't use Go escape sequences, // we treat the string as a byte sequence, and we use octal escapes. // These differences are to maintain interoperability with the other // languages' implementations of the text format. func writeString(w *textWriter, s string) error { // use WriteByte here to get any needed indent if err := w.WriteByte('"'); err != nil { return err } // Loop over the bytes, not the runes. for i := 0; i < len(s); i++ { var err error // Divergence from C++: we don't escape apostrophes. // There's no need to escape them, and the C++ parser // copes with a naked apostrophe. switch c := s[i]; c { case '\n': _, err = w.w.Write(backslashN) case '\r': _, err = w.w.Write(backslashR) case '\t': _, err = w.w.Write(backslashT) case '"': _, err = w.w.Write(backslashDQ) case '\\': _, err = w.w.Write(backslashBS) default: if isprint(c) { err = w.w.WriteByte(c) } else { _, err = fmt.Fprintf(w.w, "\\%03o", c) } } if err != nil { return err } } return w.WriteByte('"') } func writeUnknownStruct(w *textWriter, data []byte) (err error) { if !w.compact { if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil { return err } } b := NewBuffer(data) for b.index < len(b.buf) { x, err := b.DecodeVarint() if err != nil { _, ferr := fmt.Fprintf(w, "/* %v */\n", err) return ferr } wire, tag := x&7, x>>3 if wire == WireEndGroup { w.unindent() if _, werr := w.Write(endBraceNewline); werr != nil { return werr } continue } if _, ferr := fmt.Fprint(w, tag); ferr != nil { return ferr } if wire != WireStartGroup { if err = w.WriteByte(':'); err != nil { return err } } if !w.compact || wire == WireStartGroup { if err = w.WriteByte(' '); err != nil { return err } } switch wire { case WireBytes: buf, e := b.DecodeRawBytes(false) if e == nil { _, err = fmt.Fprintf(w, "%q", buf) } else { _, err = fmt.Fprintf(w, "/* %v */", e) } case WireFixed32: x, err = b.DecodeFixed32() err = writeUnknownInt(w, x, err) case WireFixed64: x, err = b.DecodeFixed64() err = writeUnknownInt(w, x, err) case WireStartGroup: err = w.WriteByte('{') w.indent() case WireVarint: x, err = b.DecodeVarint() err = writeUnknownInt(w, x, err) default: _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire) } if err != nil { return err } if err := w.WriteByte('\n'); err != nil { return err } } return nil } func writeUnknownInt(w *textWriter, x uint64, err error) error { if err == nil { _, err = fmt.Fprint(w, x) } else { _, err = fmt.Fprintf(w, "/* %v */", err) } return err } type int32Slice []int32 func (s int32Slice) Len() int { return len(s) } func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] } func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } // writeExtensions writes all the extensions in pv. // pv is assumed to be a pointer to a protocol message struct that is extendable. func (tm *TextMarshaler) writeExtensions(w *textWriter, pv reflect.Value) error { emap := extensionMaps[pv.Type().Elem()] e := pv.Interface().(Message) var m map[int32]Extension var mu sync.Locker if em, ok := e.(extensionsBytes); ok { eb := em.GetExtensions() var err error m, err = BytesToExtensionsMap(*eb) if err != nil { return err } mu = notLocker{} } else if _, ok := e.(extendableProto); ok { ep, _ := extendable(e) m, mu = ep.extensionsRead() if m == nil { return nil } } // Order the extensions by ID. // This isn't strictly necessary, but it will give us // canonical output, which will also make testing easier. mu.Lock() ids := make([]int32, 0, len(m)) for id := range m { ids = append(ids, id) } sort.Sort(int32Slice(ids)) mu.Unlock() for _, extNum := range ids { ext := m[extNum] var desc *ExtensionDesc if emap != nil { desc = emap[extNum] } if desc == nil { // Unknown extension. if err := writeUnknownStruct(w, ext.enc); err != nil { return err } continue } pb, err := GetExtension(e, desc) if err != nil { return fmt.Errorf("failed getting extension: %v", err) } // Repeated extensions will appear as a slice. if !desc.repeated() { if err := tm.writeExtension(w, desc.Name, pb); err != nil { return err } } else { v := reflect.ValueOf(pb) for i := 0; i < v.Len(); i++ { if err := tm.writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil { return err } } } } return nil } func (tm *TextMarshaler) writeExtension(w *textWriter, name string, pb interface{}) error { if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil { return err } if !w.compact { if err := w.WriteByte(' '); err != nil { return err } } if err := tm.writeAny(w, reflect.ValueOf(pb), nil); err != nil { return err } if err := w.WriteByte('\n'); err != nil { return err } return nil } func (w *textWriter) writeIndent() { if !w.complete { return } remain := w.ind * 2 for remain > 0 { n := remain if n > len(spaces) { n = len(spaces) } w.w.Write(spaces[:n]) remain -= n } w.complete = false } // TextMarshaler is a configurable text format marshaler. type TextMarshaler struct { Compact bool // use compact text format (one line). ExpandAny bool // expand google.protobuf.Any messages of known types } // Marshal writes a given protocol buffer in text format. // The only errors returned are from w. func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error { val := reflect.ValueOf(pb) if pb == nil || val.IsNil() { w.Write([]byte("<nil>")) return nil } var bw *bufio.Writer ww, ok := w.(writer) if !ok { bw = bufio.NewWriter(w) ww = bw } aw := &textWriter{ w: ww, complete: true, compact: tm.Compact, } if etm, ok := pb.(encoding.TextMarshaler); ok { text, err := etm.MarshalText() if err != nil { return err } if _, err = aw.Write(text); err != nil { return err } if bw != nil { return bw.Flush() } return nil } // Dereference the received pointer so we don't have outer < and >. v := reflect.Indirect(val) if err := tm.writeStruct(aw, v); err != nil { return err } if bw != nil { return bw.Flush() } return nil } // Text is the same as Marshal, but returns the string directly. func (tm *TextMarshaler) Text(pb Message) string { var buf bytes.Buffer tm.Marshal(&buf, pb) return buf.String() } var ( defaultTextMarshaler = TextMarshaler{} compactTextMarshaler = TextMarshaler{Compact: true} ) // TODO: consider removing some of the Marshal functions below. // MarshalText writes a given protocol buffer in text format. // The only errors returned are from w. func MarshalText(w io.Writer, pb Message) error { return defaultTextMarshaler.Marshal(w, pb) } // MarshalTextString is the same as MarshalText, but returns the string directly. func MarshalTextString(pb Message) string { return defaultTextMarshaler.Text(pb) } // CompactText writes a given protocol buffer in compact text format (one line). func CompactText(w io.Writer, pb Message) error { return compactTextMarshaler.Marshal(w, pb) } // CompactTextString is the same as CompactText, but returns the string directly. func CompactTextString(pb Message) string { return compactTextMarshaler.Text(pb) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gogo/protobuf/proto/timestamp.go
vendor/github.com/gogo/protobuf/proto/timestamp.go
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2016 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // 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. package proto // This file implements operations on google.protobuf.Timestamp. import ( "errors" "fmt" "time" ) const ( // Seconds field of the earliest valid Timestamp. // This is time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC).Unix(). minValidSeconds = -62135596800 // Seconds field just after the latest valid Timestamp. // This is time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC).Unix(). maxValidSeconds = 253402300800 ) // validateTimestamp determines whether a Timestamp is valid. // A valid timestamp represents a time in the range // [0001-01-01, 10000-01-01) and has a Nanos field // in the range [0, 1e9). // // If the Timestamp is valid, validateTimestamp returns nil. // Otherwise, it returns an error that describes // the problem. // // Every valid Timestamp can be represented by a time.Time, but the converse is not true. func validateTimestamp(ts *timestamp) error { if ts == nil { return errors.New("timestamp: nil Timestamp") } if ts.Seconds < minValidSeconds { return fmt.Errorf("timestamp: %#v before 0001-01-01", ts) } if ts.Seconds >= maxValidSeconds { return fmt.Errorf("timestamp: %#v after 10000-01-01", ts) } if ts.Nanos < 0 || ts.Nanos >= 1e9 { return fmt.Errorf("timestamp: %#v: nanos not in range [0, 1e9)", ts) } return nil } // TimestampFromProto converts a google.protobuf.Timestamp proto to a time.Time. // It returns an error if the argument is invalid. // // Unlike most Go functions, if Timestamp returns an error, the first return value // is not the zero time.Time. Instead, it is the value obtained from the // time.Unix function when passed the contents of the Timestamp, in the UTC // locale. This may or may not be a meaningful time; many invalid Timestamps // do map to valid time.Times. // // A nil Timestamp returns an error. The first return value in that case is // undefined. func timestampFromProto(ts *timestamp) (time.Time, error) { // Don't return the zero value on error, because corresponds to a valid // timestamp. Instead return whatever time.Unix gives us. var t time.Time if ts == nil { t = time.Unix(0, 0).UTC() // treat nil like the empty Timestamp } else { t = time.Unix(ts.Seconds, int64(ts.Nanos)).UTC() } return t, validateTimestamp(ts) } // TimestampProto converts the time.Time to a google.protobuf.Timestamp proto. // It returns an error if the resulting Timestamp is invalid. func timestampProto(t time.Time) (*timestamp, error) { seconds := t.Unix() nanos := int32(t.Sub(time.Unix(seconds, 0))) ts := &timestamp{ Seconds: seconds, Nanos: nanos, } if err := validateTimestamp(ts); err != nil { return nil, err } return ts, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gogo/protobuf/proto/custom_gogo.go
vendor/github.com/gogo/protobuf/proto/custom_gogo.go
// Protocol Buffers for Go with Gadgets // // Copyright (c) 2018, The GoGo Authors. All rights reserved. // http://github.com/gogo/protobuf // // 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. // // 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. package proto import "reflect" type custom interface { Marshal() ([]byte, error) Unmarshal(data []byte) error Size() int } var customType = reflect.TypeOf((*custom)(nil)).Elem()
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gogo/protobuf/proto/timestamp_gogo.go
vendor/github.com/gogo/protobuf/proto/timestamp_gogo.go
// Protocol Buffers for Go with Gadgets // // Copyright (c) 2016, The GoGo Authors. All rights reserved. // http://github.com/gogo/protobuf // // 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. // // 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. package proto import ( "reflect" "time" ) var timeType = reflect.TypeOf((*time.Time)(nil)).Elem() type timestamp struct { Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"` Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"` } func (m *timestamp) Reset() { *m = timestamp{} } func (*timestamp) ProtoMessage() {} func (*timestamp) String() string { return "timestamp<string>" } func init() { RegisterType((*timestamp)(nil), "gogo.protobuf.proto.timestamp") }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gogo/protobuf/proto/table_marshal.go
vendor/github.com/gogo/protobuf/proto/table_marshal.go
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2016 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // 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. package proto import ( "errors" "fmt" "math" "reflect" "sort" "strconv" "strings" "sync" "sync/atomic" "unicode/utf8" ) // a sizer takes a pointer to a field and the size of its tag, computes the size of // the encoded data. type sizer func(pointer, int) int // a marshaler takes a byte slice, a pointer to a field, and its tag (in wire format), // marshals the field to the end of the slice, returns the slice and error (if any). type marshaler func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) // marshalInfo is the information used for marshaling a message. type marshalInfo struct { typ reflect.Type fields []*marshalFieldInfo unrecognized field // offset of XXX_unrecognized extensions field // offset of XXX_InternalExtensions v1extensions field // offset of XXX_extensions sizecache field // offset of XXX_sizecache initialized int32 // 0 -- only typ is set, 1 -- fully initialized messageset bool // uses message set wire format hasmarshaler bool // has custom marshaler sync.RWMutex // protect extElems map, also for initialization extElems map[int32]*marshalElemInfo // info of extension elements hassizer bool // has custom sizer hasprotosizer bool // has custom protosizer bytesExtensions field // offset of XXX_extensions where the field type is []byte } // marshalFieldInfo is the information used for marshaling a field of a message. type marshalFieldInfo struct { field field wiretag uint64 // tag in wire format tagsize int // size of tag in wire format sizer sizer marshaler marshaler isPointer bool required bool // field is required name string // name of the field, for error reporting oneofElems map[reflect.Type]*marshalElemInfo // info of oneof elements } // marshalElemInfo is the information used for marshaling an extension or oneof element. type marshalElemInfo struct { wiretag uint64 // tag in wire format tagsize int // size of tag in wire format sizer sizer marshaler marshaler isptr bool // elem is pointer typed, thus interface of this type is a direct interface (extension only) } var ( marshalInfoMap = map[reflect.Type]*marshalInfo{} marshalInfoLock sync.Mutex uint8SliceType = reflect.TypeOf(([]uint8)(nil)).Kind() ) // getMarshalInfo returns the information to marshal a given type of message. // The info it returns may not necessarily initialized. // t is the type of the message (NOT the pointer to it). func getMarshalInfo(t reflect.Type) *marshalInfo { marshalInfoLock.Lock() u, ok := marshalInfoMap[t] if !ok { u = &marshalInfo{typ: t} marshalInfoMap[t] = u } marshalInfoLock.Unlock() return u } // Size is the entry point from generated code, // and should be ONLY called by generated code. // It computes the size of encoded data of msg. // a is a pointer to a place to store cached marshal info. func (a *InternalMessageInfo) Size(msg Message) int { u := getMessageMarshalInfo(msg, a) ptr := toPointer(&msg) if ptr.isNil() { // We get here if msg is a typed nil ((*SomeMessage)(nil)), // so it satisfies the interface, and msg == nil wouldn't // catch it. We don't want crash in this case. return 0 } return u.size(ptr) } // Marshal is the entry point from generated code, // and should be ONLY called by generated code. // It marshals msg to the end of b. // a is a pointer to a place to store cached marshal info. func (a *InternalMessageInfo) Marshal(b []byte, msg Message, deterministic bool) ([]byte, error) { u := getMessageMarshalInfo(msg, a) ptr := toPointer(&msg) if ptr.isNil() { // We get here if msg is a typed nil ((*SomeMessage)(nil)), // so it satisfies the interface, and msg == nil wouldn't // catch it. We don't want crash in this case. return b, ErrNil } return u.marshal(b, ptr, deterministic) } func getMessageMarshalInfo(msg interface{}, a *InternalMessageInfo) *marshalInfo { // u := a.marshal, but atomically. // We use an atomic here to ensure memory consistency. u := atomicLoadMarshalInfo(&a.marshal) if u == nil { // Get marshal information from type of message. t := reflect.ValueOf(msg).Type() if t.Kind() != reflect.Ptr { panic(fmt.Sprintf("cannot handle non-pointer message type %v", t)) } u = getMarshalInfo(t.Elem()) // Store it in the cache for later users. // a.marshal = u, but atomically. atomicStoreMarshalInfo(&a.marshal, u) } return u } // size is the main function to compute the size of the encoded data of a message. // ptr is the pointer to the message. func (u *marshalInfo) size(ptr pointer) int { if atomic.LoadInt32(&u.initialized) == 0 { u.computeMarshalInfo() } // If the message can marshal itself, let it do it, for compatibility. // NOTE: This is not efficient. if u.hasmarshaler { // Uses the message's Size method if available if u.hassizer { s := ptr.asPointerTo(u.typ).Interface().(Sizer) return s.Size() } // Uses the message's ProtoSize method if available if u.hasprotosizer { s := ptr.asPointerTo(u.typ).Interface().(ProtoSizer) return s.ProtoSize() } m := ptr.asPointerTo(u.typ).Interface().(Marshaler) b, _ := m.Marshal() return len(b) } n := 0 for _, f := range u.fields { if f.isPointer && ptr.offset(f.field).getPointer().isNil() { // nil pointer always marshals to nothing continue } n += f.sizer(ptr.offset(f.field), f.tagsize) } if u.extensions.IsValid() { e := ptr.offset(u.extensions).toExtensions() if u.messageset { n += u.sizeMessageSet(e) } else { n += u.sizeExtensions(e) } } if u.v1extensions.IsValid() { m := *ptr.offset(u.v1extensions).toOldExtensions() n += u.sizeV1Extensions(m) } if u.bytesExtensions.IsValid() { s := *ptr.offset(u.bytesExtensions).toBytes() n += len(s) } if u.unrecognized.IsValid() { s := *ptr.offset(u.unrecognized).toBytes() n += len(s) } // cache the result for use in marshal if u.sizecache.IsValid() { atomic.StoreInt32(ptr.offset(u.sizecache).toInt32(), int32(n)) } return n } // cachedsize gets the size from cache. If there is no cache (i.e. message is not generated), // fall back to compute the size. func (u *marshalInfo) cachedsize(ptr pointer) int { if u.sizecache.IsValid() { return int(atomic.LoadInt32(ptr.offset(u.sizecache).toInt32())) } return u.size(ptr) } // marshal is the main function to marshal a message. It takes a byte slice and appends // the encoded data to the end of the slice, returns the slice and error (if any). // ptr is the pointer to the message. // If deterministic is true, map is marshaled in deterministic order. func (u *marshalInfo) marshal(b []byte, ptr pointer, deterministic bool) ([]byte, error) { if atomic.LoadInt32(&u.initialized) == 0 { u.computeMarshalInfo() } // If the message can marshal itself, let it do it, for compatibility. // NOTE: This is not efficient. if u.hasmarshaler { m := ptr.asPointerTo(u.typ).Interface().(Marshaler) b1, err := m.Marshal() b = append(b, b1...) return b, err } var err, errLater error // The old marshaler encodes extensions at beginning. if u.extensions.IsValid() { e := ptr.offset(u.extensions).toExtensions() if u.messageset { b, err = u.appendMessageSet(b, e, deterministic) } else { b, err = u.appendExtensions(b, e, deterministic) } if err != nil { return b, err } } if u.v1extensions.IsValid() { m := *ptr.offset(u.v1extensions).toOldExtensions() b, err = u.appendV1Extensions(b, m, deterministic) if err != nil { return b, err } } if u.bytesExtensions.IsValid() { s := *ptr.offset(u.bytesExtensions).toBytes() b = append(b, s...) } for _, f := range u.fields { if f.required { if f.isPointer && ptr.offset(f.field).getPointer().isNil() { // Required field is not set. // We record the error but keep going, to give a complete marshaling. if errLater == nil { errLater = &RequiredNotSetError{f.name} } continue } } if f.isPointer && ptr.offset(f.field).getPointer().isNil() { // nil pointer always marshals to nothing continue } b, err = f.marshaler(b, ptr.offset(f.field), f.wiretag, deterministic) if err != nil { if err1, ok := err.(*RequiredNotSetError); ok { // Required field in submessage is not set. // We record the error but keep going, to give a complete marshaling. if errLater == nil { errLater = &RequiredNotSetError{f.name + "." + err1.field} } continue } if err == errRepeatedHasNil { err = errors.New("proto: repeated field " + f.name + " has nil element") } if err == errInvalidUTF8 { if errLater == nil { fullName := revProtoTypes[reflect.PtrTo(u.typ)] + "." + f.name errLater = &invalidUTF8Error{fullName} } continue } return b, err } } if u.unrecognized.IsValid() { s := *ptr.offset(u.unrecognized).toBytes() b = append(b, s...) } return b, errLater } // computeMarshalInfo initializes the marshal info. func (u *marshalInfo) computeMarshalInfo() { u.Lock() defer u.Unlock() if u.initialized != 0 { // non-atomic read is ok as it is protected by the lock return } t := u.typ u.unrecognized = invalidField u.extensions = invalidField u.v1extensions = invalidField u.bytesExtensions = invalidField u.sizecache = invalidField isOneofMessage := false if reflect.PtrTo(t).Implements(sizerType) { u.hassizer = true } if reflect.PtrTo(t).Implements(protosizerType) { u.hasprotosizer = true } // If the message can marshal itself, let it do it, for compatibility. // NOTE: This is not efficient. if reflect.PtrTo(t).Implements(marshalerType) { u.hasmarshaler = true atomic.StoreInt32(&u.initialized, 1) return } n := t.NumField() // deal with XXX fields first for i := 0; i < t.NumField(); i++ { f := t.Field(i) if f.Tag.Get("protobuf_oneof") != "" { isOneofMessage = true } if !strings.HasPrefix(f.Name, "XXX_") { continue } switch f.Name { case "XXX_sizecache": u.sizecache = toField(&f) case "XXX_unrecognized": u.unrecognized = toField(&f) case "XXX_InternalExtensions": u.extensions = toField(&f) u.messageset = f.Tag.Get("protobuf_messageset") == "1" case "XXX_extensions": if f.Type.Kind() == reflect.Map { u.v1extensions = toField(&f) } else { u.bytesExtensions = toField(&f) } case "XXX_NoUnkeyedLiteral": // nothing to do default: panic("unknown XXX field: " + f.Name) } n-- } // get oneof implementers var oneofImplementers []interface{} // gogo: isOneofMessage is needed for embedded oneof messages, without a marshaler and unmarshaler if isOneofMessage { switch m := reflect.Zero(reflect.PtrTo(t)).Interface().(type) { case oneofFuncsIface: _, _, _, oneofImplementers = m.XXX_OneofFuncs() case oneofWrappersIface: oneofImplementers = m.XXX_OneofWrappers() } } // normal fields fields := make([]marshalFieldInfo, n) // batch allocation u.fields = make([]*marshalFieldInfo, 0, n) for i, j := 0, 0; i < t.NumField(); i++ { f := t.Field(i) if strings.HasPrefix(f.Name, "XXX_") { continue } field := &fields[j] j++ field.name = f.Name u.fields = append(u.fields, field) if f.Tag.Get("protobuf_oneof") != "" { field.computeOneofFieldInfo(&f, oneofImplementers) continue } if f.Tag.Get("protobuf") == "" { // field has no tag (not in generated message), ignore it u.fields = u.fields[:len(u.fields)-1] j-- continue } field.computeMarshalFieldInfo(&f) } // fields are marshaled in tag order on the wire. sort.Sort(byTag(u.fields)) atomic.StoreInt32(&u.initialized, 1) } // helper for sorting fields by tag type byTag []*marshalFieldInfo func (a byTag) Len() int { return len(a) } func (a byTag) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a byTag) Less(i, j int) bool { return a[i].wiretag < a[j].wiretag } // getExtElemInfo returns the information to marshal an extension element. // The info it returns is initialized. func (u *marshalInfo) getExtElemInfo(desc *ExtensionDesc) *marshalElemInfo { // get from cache first u.RLock() e, ok := u.extElems[desc.Field] u.RUnlock() if ok { return e } t := reflect.TypeOf(desc.ExtensionType) // pointer or slice to basic type or struct tags := strings.Split(desc.Tag, ",") tag, err := strconv.Atoi(tags[1]) if err != nil { panic("tag is not an integer") } wt := wiretype(tags[0]) sizr, marshalr := typeMarshaler(t, tags, false, false) e = &marshalElemInfo{ wiretag: uint64(tag)<<3 | wt, tagsize: SizeVarint(uint64(tag) << 3), sizer: sizr, marshaler: marshalr, isptr: t.Kind() == reflect.Ptr, } // update cache u.Lock() if u.extElems == nil { u.extElems = make(map[int32]*marshalElemInfo) } u.extElems[desc.Field] = e u.Unlock() return e } // computeMarshalFieldInfo fills up the information to marshal a field. func (fi *marshalFieldInfo) computeMarshalFieldInfo(f *reflect.StructField) { // parse protobuf tag of the field. // tag has format of "bytes,49,opt,name=foo,def=hello!" tags := strings.Split(f.Tag.Get("protobuf"), ",") if tags[0] == "" { return } tag, err := strconv.Atoi(tags[1]) if err != nil { panic("tag is not an integer") } wt := wiretype(tags[0]) if tags[2] == "req" { fi.required = true } fi.setTag(f, tag, wt) fi.setMarshaler(f, tags) } func (fi *marshalFieldInfo) computeOneofFieldInfo(f *reflect.StructField, oneofImplementers []interface{}) { fi.field = toField(f) fi.wiretag = math.MaxInt32 // Use a large tag number, make oneofs sorted at the end. This tag will not appear on the wire. fi.isPointer = true fi.sizer, fi.marshaler = makeOneOfMarshaler(fi, f) fi.oneofElems = make(map[reflect.Type]*marshalElemInfo) ityp := f.Type // interface type for _, o := range oneofImplementers { t := reflect.TypeOf(o) if !t.Implements(ityp) { continue } sf := t.Elem().Field(0) // oneof implementer is a struct with a single field tags := strings.Split(sf.Tag.Get("protobuf"), ",") tag, err := strconv.Atoi(tags[1]) if err != nil { panic("tag is not an integer") } wt := wiretype(tags[0]) sizr, marshalr := typeMarshaler(sf.Type, tags, false, true) // oneof should not omit any zero value fi.oneofElems[t.Elem()] = &marshalElemInfo{ wiretag: uint64(tag)<<3 | wt, tagsize: SizeVarint(uint64(tag) << 3), sizer: sizr, marshaler: marshalr, } } } // wiretype returns the wire encoding of the type. func wiretype(encoding string) uint64 { switch encoding { case "fixed32": return WireFixed32 case "fixed64": return WireFixed64 case "varint", "zigzag32", "zigzag64": return WireVarint case "bytes": return WireBytes case "group": return WireStartGroup } panic("unknown wire type " + encoding) } // setTag fills up the tag (in wire format) and its size in the info of a field. func (fi *marshalFieldInfo) setTag(f *reflect.StructField, tag int, wt uint64) { fi.field = toField(f) fi.wiretag = uint64(tag)<<3 | wt fi.tagsize = SizeVarint(uint64(tag) << 3) } // setMarshaler fills up the sizer and marshaler in the info of a field. func (fi *marshalFieldInfo) setMarshaler(f *reflect.StructField, tags []string) { switch f.Type.Kind() { case reflect.Map: // map field fi.isPointer = true fi.sizer, fi.marshaler = makeMapMarshaler(f) return case reflect.Ptr, reflect.Slice: fi.isPointer = true } fi.sizer, fi.marshaler = typeMarshaler(f.Type, tags, true, false) } // typeMarshaler returns the sizer and marshaler of a given field. // t is the type of the field. // tags is the generated "protobuf" tag of the field. // If nozero is true, zero value is not marshaled to the wire. // If oneof is true, it is a oneof field. func typeMarshaler(t reflect.Type, tags []string, nozero, oneof bool) (sizer, marshaler) { encoding := tags[0] pointer := false slice := false if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 { slice = true t = t.Elem() } if t.Kind() == reflect.Ptr { pointer = true t = t.Elem() } packed := false proto3 := false ctype := false isTime := false isDuration := false isWktPointer := false validateUTF8 := true for i := 2; i < len(tags); i++ { if tags[i] == "packed" { packed = true } if tags[i] == "proto3" { proto3 = true } if strings.HasPrefix(tags[i], "customtype=") { ctype = true } if tags[i] == "stdtime" { isTime = true } if tags[i] == "stdduration" { isDuration = true } if tags[i] == "wktptr" { isWktPointer = true } } validateUTF8 = validateUTF8 && proto3 if !proto3 && !pointer && !slice { nozero = false } if ctype { if reflect.PtrTo(t).Implements(customType) { if slice { return makeMessageRefSliceMarshaler(getMarshalInfo(t)) } if pointer { return makeCustomPtrMarshaler(getMarshalInfo(t)) } return makeCustomMarshaler(getMarshalInfo(t)) } else { panic(fmt.Sprintf("custom type: type: %v, does not implement the proto.custom interface", t)) } } if isTime { if pointer { if slice { return makeTimePtrSliceMarshaler(getMarshalInfo(t)) } return makeTimePtrMarshaler(getMarshalInfo(t)) } if slice { return makeTimeSliceMarshaler(getMarshalInfo(t)) } return makeTimeMarshaler(getMarshalInfo(t)) } if isDuration { if pointer { if slice { return makeDurationPtrSliceMarshaler(getMarshalInfo(t)) } return makeDurationPtrMarshaler(getMarshalInfo(t)) } if slice { return makeDurationSliceMarshaler(getMarshalInfo(t)) } return makeDurationMarshaler(getMarshalInfo(t)) } if isWktPointer { switch t.Kind() { case reflect.Float64: if pointer { if slice { return makeStdDoubleValuePtrSliceMarshaler(getMarshalInfo(t)) } return makeStdDoubleValuePtrMarshaler(getMarshalInfo(t)) } if slice { return makeStdDoubleValueSliceMarshaler(getMarshalInfo(t)) } return makeStdDoubleValueMarshaler(getMarshalInfo(t)) case reflect.Float32: if pointer { if slice { return makeStdFloatValuePtrSliceMarshaler(getMarshalInfo(t)) } return makeStdFloatValuePtrMarshaler(getMarshalInfo(t)) } if slice { return makeStdFloatValueSliceMarshaler(getMarshalInfo(t)) } return makeStdFloatValueMarshaler(getMarshalInfo(t)) case reflect.Int64: if pointer { if slice { return makeStdInt64ValuePtrSliceMarshaler(getMarshalInfo(t)) } return makeStdInt64ValuePtrMarshaler(getMarshalInfo(t)) } if slice { return makeStdInt64ValueSliceMarshaler(getMarshalInfo(t)) } return makeStdInt64ValueMarshaler(getMarshalInfo(t)) case reflect.Uint64: if pointer { if slice { return makeStdUInt64ValuePtrSliceMarshaler(getMarshalInfo(t)) } return makeStdUInt64ValuePtrMarshaler(getMarshalInfo(t)) } if slice { return makeStdUInt64ValueSliceMarshaler(getMarshalInfo(t)) } return makeStdUInt64ValueMarshaler(getMarshalInfo(t)) case reflect.Int32: if pointer { if slice { return makeStdInt32ValuePtrSliceMarshaler(getMarshalInfo(t)) } return makeStdInt32ValuePtrMarshaler(getMarshalInfo(t)) } if slice { return makeStdInt32ValueSliceMarshaler(getMarshalInfo(t)) } return makeStdInt32ValueMarshaler(getMarshalInfo(t)) case reflect.Uint32: if pointer { if slice { return makeStdUInt32ValuePtrSliceMarshaler(getMarshalInfo(t)) } return makeStdUInt32ValuePtrMarshaler(getMarshalInfo(t)) } if slice { return makeStdUInt32ValueSliceMarshaler(getMarshalInfo(t)) } return makeStdUInt32ValueMarshaler(getMarshalInfo(t)) case reflect.Bool: if pointer { if slice { return makeStdBoolValuePtrSliceMarshaler(getMarshalInfo(t)) } return makeStdBoolValuePtrMarshaler(getMarshalInfo(t)) } if slice { return makeStdBoolValueSliceMarshaler(getMarshalInfo(t)) } return makeStdBoolValueMarshaler(getMarshalInfo(t)) case reflect.String: if pointer { if slice { return makeStdStringValuePtrSliceMarshaler(getMarshalInfo(t)) } return makeStdStringValuePtrMarshaler(getMarshalInfo(t)) } if slice { return makeStdStringValueSliceMarshaler(getMarshalInfo(t)) } return makeStdStringValueMarshaler(getMarshalInfo(t)) case uint8SliceType: if pointer { if slice { return makeStdBytesValuePtrSliceMarshaler(getMarshalInfo(t)) } return makeStdBytesValuePtrMarshaler(getMarshalInfo(t)) } if slice { return makeStdBytesValueSliceMarshaler(getMarshalInfo(t)) } return makeStdBytesValueMarshaler(getMarshalInfo(t)) default: panic(fmt.Sprintf("unknown wktpointer type %#v", t)) } } switch t.Kind() { case reflect.Bool: if pointer { return sizeBoolPtr, appendBoolPtr } if slice { if packed { return sizeBoolPackedSlice, appendBoolPackedSlice } return sizeBoolSlice, appendBoolSlice } if nozero { return sizeBoolValueNoZero, appendBoolValueNoZero } return sizeBoolValue, appendBoolValue case reflect.Uint32: switch encoding { case "fixed32": if pointer { return sizeFixed32Ptr, appendFixed32Ptr } if slice { if packed { return sizeFixed32PackedSlice, appendFixed32PackedSlice } return sizeFixed32Slice, appendFixed32Slice } if nozero { return sizeFixed32ValueNoZero, appendFixed32ValueNoZero } return sizeFixed32Value, appendFixed32Value case "varint": if pointer { return sizeVarint32Ptr, appendVarint32Ptr } if slice { if packed { return sizeVarint32PackedSlice, appendVarint32PackedSlice } return sizeVarint32Slice, appendVarint32Slice } if nozero { return sizeVarint32ValueNoZero, appendVarint32ValueNoZero } return sizeVarint32Value, appendVarint32Value } case reflect.Int32: switch encoding { case "fixed32": if pointer { return sizeFixedS32Ptr, appendFixedS32Ptr } if slice { if packed { return sizeFixedS32PackedSlice, appendFixedS32PackedSlice } return sizeFixedS32Slice, appendFixedS32Slice } if nozero { return sizeFixedS32ValueNoZero, appendFixedS32ValueNoZero } return sizeFixedS32Value, appendFixedS32Value case "varint": if pointer { return sizeVarintS32Ptr, appendVarintS32Ptr } if slice { if packed { return sizeVarintS32PackedSlice, appendVarintS32PackedSlice } return sizeVarintS32Slice, appendVarintS32Slice } if nozero { return sizeVarintS32ValueNoZero, appendVarintS32ValueNoZero } return sizeVarintS32Value, appendVarintS32Value case "zigzag32": if pointer { return sizeZigzag32Ptr, appendZigzag32Ptr } if slice { if packed { return sizeZigzag32PackedSlice, appendZigzag32PackedSlice } return sizeZigzag32Slice, appendZigzag32Slice } if nozero { return sizeZigzag32ValueNoZero, appendZigzag32ValueNoZero } return sizeZigzag32Value, appendZigzag32Value } case reflect.Uint64: switch encoding { case "fixed64": if pointer { return sizeFixed64Ptr, appendFixed64Ptr } if slice { if packed { return sizeFixed64PackedSlice, appendFixed64PackedSlice } return sizeFixed64Slice, appendFixed64Slice } if nozero { return sizeFixed64ValueNoZero, appendFixed64ValueNoZero } return sizeFixed64Value, appendFixed64Value case "varint": if pointer { return sizeVarint64Ptr, appendVarint64Ptr } if slice { if packed { return sizeVarint64PackedSlice, appendVarint64PackedSlice } return sizeVarint64Slice, appendVarint64Slice } if nozero { return sizeVarint64ValueNoZero, appendVarint64ValueNoZero } return sizeVarint64Value, appendVarint64Value } case reflect.Int64: switch encoding { case "fixed64": if pointer { return sizeFixedS64Ptr, appendFixedS64Ptr } if slice { if packed { return sizeFixedS64PackedSlice, appendFixedS64PackedSlice } return sizeFixedS64Slice, appendFixedS64Slice } if nozero { return sizeFixedS64ValueNoZero, appendFixedS64ValueNoZero } return sizeFixedS64Value, appendFixedS64Value case "varint": if pointer { return sizeVarintS64Ptr, appendVarintS64Ptr } if slice { if packed { return sizeVarintS64PackedSlice, appendVarintS64PackedSlice } return sizeVarintS64Slice, appendVarintS64Slice } if nozero { return sizeVarintS64ValueNoZero, appendVarintS64ValueNoZero } return sizeVarintS64Value, appendVarintS64Value case "zigzag64": if pointer { return sizeZigzag64Ptr, appendZigzag64Ptr } if slice { if packed { return sizeZigzag64PackedSlice, appendZigzag64PackedSlice } return sizeZigzag64Slice, appendZigzag64Slice } if nozero { return sizeZigzag64ValueNoZero, appendZigzag64ValueNoZero } return sizeZigzag64Value, appendZigzag64Value } case reflect.Float32: if pointer { return sizeFloat32Ptr, appendFloat32Ptr } if slice { if packed { return sizeFloat32PackedSlice, appendFloat32PackedSlice } return sizeFloat32Slice, appendFloat32Slice } if nozero { return sizeFloat32ValueNoZero, appendFloat32ValueNoZero } return sizeFloat32Value, appendFloat32Value case reflect.Float64: if pointer { return sizeFloat64Ptr, appendFloat64Ptr } if slice { if packed { return sizeFloat64PackedSlice, appendFloat64PackedSlice } return sizeFloat64Slice, appendFloat64Slice } if nozero { return sizeFloat64ValueNoZero, appendFloat64ValueNoZero } return sizeFloat64Value, appendFloat64Value case reflect.String: if validateUTF8 { if pointer { return sizeStringPtr, appendUTF8StringPtr } if slice { return sizeStringSlice, appendUTF8StringSlice } if nozero { return sizeStringValueNoZero, appendUTF8StringValueNoZero } return sizeStringValue, appendUTF8StringValue } if pointer { return sizeStringPtr, appendStringPtr } if slice { return sizeStringSlice, appendStringSlice } if nozero { return sizeStringValueNoZero, appendStringValueNoZero } return sizeStringValue, appendStringValue case reflect.Slice: if slice { return sizeBytesSlice, appendBytesSlice } if oneof { // Oneof bytes field may also have "proto3" tag. // We want to marshal it as a oneof field. Do this // check before the proto3 check. return sizeBytesOneof, appendBytesOneof } if proto3 { return sizeBytes3, appendBytes3 } return sizeBytes, appendBytes case reflect.Struct: switch encoding { case "group": if slice { return makeGroupSliceMarshaler(getMarshalInfo(t)) } return makeGroupMarshaler(getMarshalInfo(t)) case "bytes": if pointer { if slice { return makeMessageSliceMarshaler(getMarshalInfo(t)) } return makeMessageMarshaler(getMarshalInfo(t)) } else { if slice { return makeMessageRefSliceMarshaler(getMarshalInfo(t)) } return makeMessageRefMarshaler(getMarshalInfo(t)) } } } panic(fmt.Sprintf("unknown or mismatched type: type: %v, wire type: %v", t, encoding)) } // Below are functions to size/marshal a specific type of a field. // They are stored in the field's info, and called by function pointers. // They have type sizer or marshaler. func sizeFixed32Value(_ pointer, tagsize int) int { return 4 + tagsize } func sizeFixed32ValueNoZero(ptr pointer, tagsize int) int { v := *ptr.toUint32() if v == 0 { return 0 } return 4 + tagsize } func sizeFixed32Ptr(ptr pointer, tagsize int) int { p := *ptr.toUint32Ptr() if p == nil { return 0 } return 4 + tagsize } func sizeFixed32Slice(ptr pointer, tagsize int) int { s := *ptr.toUint32Slice() return (4 + tagsize) * len(s) } func sizeFixed32PackedSlice(ptr pointer, tagsize int) int { s := *ptr.toUint32Slice() if len(s) == 0 { return 0 } return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize } func sizeFixedS32Value(_ pointer, tagsize int) int { return 4 + tagsize } func sizeFixedS32ValueNoZero(ptr pointer, tagsize int) int { v := *ptr.toInt32() if v == 0 { return 0 } return 4 + tagsize } func sizeFixedS32Ptr(ptr pointer, tagsize int) int { p := ptr.getInt32Ptr() if p == nil { return 0 } return 4 + tagsize } func sizeFixedS32Slice(ptr pointer, tagsize int) int { s := ptr.getInt32Slice() return (4 + tagsize) * len(s) } func sizeFixedS32PackedSlice(ptr pointer, tagsize int) int { s := ptr.getInt32Slice() if len(s) == 0 { return 0 } return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize } func sizeFloat32Value(_ pointer, tagsize int) int { return 4 + tagsize } func sizeFloat32ValueNoZero(ptr pointer, tagsize int) int { v := math.Float32bits(*ptr.toFloat32()) if v == 0 { return 0 } return 4 + tagsize } func sizeFloat32Ptr(ptr pointer, tagsize int) int { p := *ptr.toFloat32Ptr() if p == nil { return 0 } return 4 + tagsize } func sizeFloat32Slice(ptr pointer, tagsize int) int { s := *ptr.toFloat32Slice() return (4 + tagsize) * len(s) } func sizeFloat32PackedSlice(ptr pointer, tagsize int) int { s := *ptr.toFloat32Slice() if len(s) == 0 { return 0 } return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize } func sizeFixed64Value(_ pointer, tagsize int) int { return 8 + tagsize } func sizeFixed64ValueNoZero(ptr pointer, tagsize int) int { v := *ptr.toUint64() if v == 0 { return 0 } return 8 + tagsize } func sizeFixed64Ptr(ptr pointer, tagsize int) int { p := *ptr.toUint64Ptr() if p == nil { return 0 } return 8 + tagsize } func sizeFixed64Slice(ptr pointer, tagsize int) int { s := *ptr.toUint64Slice() return (8 + tagsize) * len(s) } func sizeFixed64PackedSlice(ptr pointer, tagsize int) int { s := *ptr.toUint64Slice() if len(s) == 0 { return 0 } return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize } func sizeFixedS64Value(_ pointer, tagsize int) int { return 8 + tagsize } func sizeFixedS64ValueNoZero(ptr pointer, tagsize int) int { v := *ptr.toInt64() if v == 0 { return 0 } return 8 + tagsize } func sizeFixedS64Ptr(ptr pointer, tagsize int) int { p := *ptr.toInt64Ptr() if p == nil { return 0 } return 8 + tagsize } func sizeFixedS64Slice(ptr pointer, tagsize int) int { s := *ptr.toInt64Slice() return (8 + tagsize) * len(s) } func sizeFixedS64PackedSlice(ptr pointer, tagsize int) int { s := *ptr.toInt64Slice() if len(s) == 0 { return 0 } return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize } func sizeFloat64Value(_ pointer, tagsize int) int { return 8 + tagsize } func sizeFloat64ValueNoZero(ptr pointer, tagsize int) int { v := math.Float64bits(*ptr.toFloat64()) if v == 0 { return 0 } return 8 + tagsize } func sizeFloat64Ptr(ptr pointer, tagsize int) int { p := *ptr.toFloat64Ptr() if p == nil { return 0 } return 8 + tagsize } func sizeFloat64Slice(ptr pointer, tagsize int) int { s := *ptr.toFloat64Slice()
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gogo/protobuf/proto/table_unmarshal.go
vendor/github.com/gogo/protobuf/proto/table_unmarshal.go
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2016 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // 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. package proto import ( "errors" "fmt" "io" "math" "reflect" "strconv" "strings" "sync" "sync/atomic" "unicode/utf8" ) // Unmarshal is the entry point from the generated .pb.go files. // This function is not intended to be used by non-generated code. // This function is not subject to any compatibility guarantee. // msg contains a pointer to a protocol buffer struct. // b is the data to be unmarshaled into the protocol buffer. // a is a pointer to a place to store cached unmarshal information. func (a *InternalMessageInfo) Unmarshal(msg Message, b []byte) error { // Load the unmarshal information for this message type. // The atomic load ensures memory consistency. u := atomicLoadUnmarshalInfo(&a.unmarshal) if u == nil { // Slow path: find unmarshal info for msg, update a with it. u = getUnmarshalInfo(reflect.TypeOf(msg).Elem()) atomicStoreUnmarshalInfo(&a.unmarshal, u) } // Then do the unmarshaling. err := u.unmarshal(toPointer(&msg), b) return err } type unmarshalInfo struct { typ reflect.Type // type of the protobuf struct // 0 = only typ field is initialized // 1 = completely initialized initialized int32 lock sync.Mutex // prevents double initialization dense []unmarshalFieldInfo // fields indexed by tag # sparse map[uint64]unmarshalFieldInfo // fields indexed by tag # reqFields []string // names of required fields reqMask uint64 // 1<<len(reqFields)-1 unrecognized field // offset of []byte to put unrecognized data (or invalidField if we should throw it away) extensions field // offset of extensions field (of type proto.XXX_InternalExtensions), or invalidField if it does not exist oldExtensions field // offset of old-form extensions field (of type map[int]Extension) extensionRanges []ExtensionRange // if non-nil, implies extensions field is valid isMessageSet bool // if true, implies extensions field is valid bytesExtensions field // offset of XXX_extensions with type []byte } // An unmarshaler takes a stream of bytes and a pointer to a field of a message. // It decodes the field, stores it at f, and returns the unused bytes. // w is the wire encoding. // b is the data after the tag and wire encoding have been read. type unmarshaler func(b []byte, f pointer, w int) ([]byte, error) type unmarshalFieldInfo struct { // location of the field in the proto message structure. field field // function to unmarshal the data for the field. unmarshal unmarshaler // if a required field, contains a single set bit at this field's index in the required field list. reqMask uint64 name string // name of the field, for error reporting } var ( unmarshalInfoMap = map[reflect.Type]*unmarshalInfo{} unmarshalInfoLock sync.Mutex ) // getUnmarshalInfo returns the data structure which can be // subsequently used to unmarshal a message of the given type. // t is the type of the message (note: not pointer to message). func getUnmarshalInfo(t reflect.Type) *unmarshalInfo { // It would be correct to return a new unmarshalInfo // unconditionally. We would end up allocating one // per occurrence of that type as a message or submessage. // We use a cache here just to reduce memory usage. unmarshalInfoLock.Lock() defer unmarshalInfoLock.Unlock() u := unmarshalInfoMap[t] if u == nil { u = &unmarshalInfo{typ: t} // Note: we just set the type here. The rest of the fields // will be initialized on first use. unmarshalInfoMap[t] = u } return u } // unmarshal does the main work of unmarshaling a message. // u provides type information used to unmarshal the message. // m is a pointer to a protocol buffer message. // b is a byte stream to unmarshal into m. // This is top routine used when recursively unmarshaling submessages. func (u *unmarshalInfo) unmarshal(m pointer, b []byte) error { if atomic.LoadInt32(&u.initialized) == 0 { u.computeUnmarshalInfo() } if u.isMessageSet { return unmarshalMessageSet(b, m.offset(u.extensions).toExtensions()) } var reqMask uint64 // bitmask of required fields we've seen. var errLater error for len(b) > 0 { // Read tag and wire type. // Special case 1 and 2 byte varints. var x uint64 if b[0] < 128 { x = uint64(b[0]) b = b[1:] } else if len(b) >= 2 && b[1] < 128 { x = uint64(b[0]&0x7f) + uint64(b[1])<<7 b = b[2:] } else { var n int x, n = decodeVarint(b) if n == 0 { return io.ErrUnexpectedEOF } b = b[n:] } tag := x >> 3 wire := int(x) & 7 // Dispatch on the tag to one of the unmarshal* functions below. var f unmarshalFieldInfo if tag < uint64(len(u.dense)) { f = u.dense[tag] } else { f = u.sparse[tag] } if fn := f.unmarshal; fn != nil { var err error b, err = fn(b, m.offset(f.field), wire) if err == nil { reqMask |= f.reqMask continue } if r, ok := err.(*RequiredNotSetError); ok { // Remember this error, but keep parsing. We need to produce // a full parse even if a required field is missing. if errLater == nil { errLater = r } reqMask |= f.reqMask continue } if err != errInternalBadWireType { if err == errInvalidUTF8 { if errLater == nil { fullName := revProtoTypes[reflect.PtrTo(u.typ)] + "." + f.name errLater = &invalidUTF8Error{fullName} } continue } return err } // Fragments with bad wire type are treated as unknown fields. } // Unknown tag. if !u.unrecognized.IsValid() { // Don't keep unrecognized data; just skip it. var err error b, err = skipField(b, wire) if err != nil { return err } continue } // Keep unrecognized data around. // maybe in extensions, maybe in the unrecognized field. z := m.offset(u.unrecognized).toBytes() var emap map[int32]Extension var e Extension for _, r := range u.extensionRanges { if uint64(r.Start) <= tag && tag <= uint64(r.End) { if u.extensions.IsValid() { mp := m.offset(u.extensions).toExtensions() emap = mp.extensionsWrite() e = emap[int32(tag)] z = &e.enc break } if u.oldExtensions.IsValid() { p := m.offset(u.oldExtensions).toOldExtensions() emap = *p if emap == nil { emap = map[int32]Extension{} *p = emap } e = emap[int32(tag)] z = &e.enc break } if u.bytesExtensions.IsValid() { z = m.offset(u.bytesExtensions).toBytes() break } panic("no extensions field available") } } // Use wire type to skip data. var err error b0 := b b, err = skipField(b, wire) if err != nil { return err } *z = encodeVarint(*z, tag<<3|uint64(wire)) *z = append(*z, b0[:len(b0)-len(b)]...) if emap != nil { emap[int32(tag)] = e } } if reqMask != u.reqMask && errLater == nil { // A required field of this message is missing. for _, n := range u.reqFields { if reqMask&1 == 0 { errLater = &RequiredNotSetError{n} } reqMask >>= 1 } } return errLater } // computeUnmarshalInfo fills in u with information for use // in unmarshaling protocol buffers of type u.typ. func (u *unmarshalInfo) computeUnmarshalInfo() { u.lock.Lock() defer u.lock.Unlock() if u.initialized != 0 { return } t := u.typ n := t.NumField() // Set up the "not found" value for the unrecognized byte buffer. // This is the default for proto3. u.unrecognized = invalidField u.extensions = invalidField u.oldExtensions = invalidField u.bytesExtensions = invalidField // List of the generated type and offset for each oneof field. type oneofField struct { ityp reflect.Type // interface type of oneof field field field // offset in containing message } var oneofFields []oneofField for i := 0; i < n; i++ { f := t.Field(i) if f.Name == "XXX_unrecognized" { // The byte slice used to hold unrecognized input is special. if f.Type != reflect.TypeOf(([]byte)(nil)) { panic("bad type for XXX_unrecognized field: " + f.Type.Name()) } u.unrecognized = toField(&f) continue } if f.Name == "XXX_InternalExtensions" { // Ditto here. if f.Type != reflect.TypeOf(XXX_InternalExtensions{}) { panic("bad type for XXX_InternalExtensions field: " + f.Type.Name()) } u.extensions = toField(&f) if f.Tag.Get("protobuf_messageset") == "1" { u.isMessageSet = true } continue } if f.Name == "XXX_extensions" { // An older form of the extensions field. if f.Type == reflect.TypeOf((map[int32]Extension)(nil)) { u.oldExtensions = toField(&f) continue } else if f.Type == reflect.TypeOf(([]byte)(nil)) { u.bytesExtensions = toField(&f) continue } panic("bad type for XXX_extensions field: " + f.Type.Name()) } if f.Name == "XXX_NoUnkeyedLiteral" || f.Name == "XXX_sizecache" { continue } oneof := f.Tag.Get("protobuf_oneof") if oneof != "" { oneofFields = append(oneofFields, oneofField{f.Type, toField(&f)}) // The rest of oneof processing happens below. continue } tags := f.Tag.Get("protobuf") tagArray := strings.Split(tags, ",") if len(tagArray) < 2 { panic("protobuf tag not enough fields in " + t.Name() + "." + f.Name + ": " + tags) } tag, err := strconv.Atoi(tagArray[1]) if err != nil { panic("protobuf tag field not an integer: " + tagArray[1]) } name := "" for _, tag := range tagArray[3:] { if strings.HasPrefix(tag, "name=") { name = tag[5:] } } // Extract unmarshaling function from the field (its type and tags). unmarshal := fieldUnmarshaler(&f) // Required field? var reqMask uint64 if tagArray[2] == "req" { bit := len(u.reqFields) u.reqFields = append(u.reqFields, name) reqMask = uint64(1) << uint(bit) // TODO: if we have more than 64 required fields, we end up // not verifying that all required fields are present. // Fix this, perhaps using a count of required fields? } // Store the info in the correct slot in the message. u.setTag(tag, toField(&f), unmarshal, reqMask, name) } // Find any types associated with oneof fields. // gogo: len(oneofFields) > 0 is needed for embedded oneof messages, without a marshaler and unmarshaler if len(oneofFields) > 0 { var oneofImplementers []interface{} switch m := reflect.Zero(reflect.PtrTo(t)).Interface().(type) { case oneofFuncsIface: _, _, _, oneofImplementers = m.XXX_OneofFuncs() case oneofWrappersIface: oneofImplementers = m.XXX_OneofWrappers() } for _, v := range oneofImplementers { tptr := reflect.TypeOf(v) // *Msg_X typ := tptr.Elem() // Msg_X f := typ.Field(0) // oneof implementers have one field baseUnmarshal := fieldUnmarshaler(&f) tags := strings.Split(f.Tag.Get("protobuf"), ",") fieldNum, err := strconv.Atoi(tags[1]) if err != nil { panic("protobuf tag field not an integer: " + tags[1]) } var name string for _, tag := range tags { if strings.HasPrefix(tag, "name=") { name = strings.TrimPrefix(tag, "name=") break } } // Find the oneof field that this struct implements. // Might take O(n^2) to process all of the oneofs, but who cares. for _, of := range oneofFields { if tptr.Implements(of.ityp) { // We have found the corresponding interface for this struct. // That lets us know where this struct should be stored // when we encounter it during unmarshaling. unmarshal := makeUnmarshalOneof(typ, of.ityp, baseUnmarshal) u.setTag(fieldNum, of.field, unmarshal, 0, name) } } } } // Get extension ranges, if any. fn := reflect.Zero(reflect.PtrTo(t)).MethodByName("ExtensionRangeArray") if fn.IsValid() { if !u.extensions.IsValid() && !u.oldExtensions.IsValid() && !u.bytesExtensions.IsValid() { panic("a message with extensions, but no extensions field in " + t.Name()) } u.extensionRanges = fn.Call(nil)[0].Interface().([]ExtensionRange) } // Explicitly disallow tag 0. This will ensure we flag an error // when decoding a buffer of all zeros. Without this code, we // would decode and skip an all-zero buffer of even length. // [0 0] is [tag=0/wiretype=varint varint-encoded-0]. u.setTag(0, zeroField, func(b []byte, f pointer, w int) ([]byte, error) { return nil, fmt.Errorf("proto: %s: illegal tag 0 (wire type %d)", t, w) }, 0, "") // Set mask for required field check. u.reqMask = uint64(1)<<uint(len(u.reqFields)) - 1 atomic.StoreInt32(&u.initialized, 1) } // setTag stores the unmarshal information for the given tag. // tag = tag # for field // field/unmarshal = unmarshal info for that field. // reqMask = if required, bitmask for field position in required field list. 0 otherwise. // name = short name of the field. func (u *unmarshalInfo) setTag(tag int, field field, unmarshal unmarshaler, reqMask uint64, name string) { i := unmarshalFieldInfo{field: field, unmarshal: unmarshal, reqMask: reqMask, name: name} n := u.typ.NumField() if tag >= 0 && (tag < 16 || tag < 2*n) { // TODO: what are the right numbers here? for len(u.dense) <= tag { u.dense = append(u.dense, unmarshalFieldInfo{}) } u.dense[tag] = i return } if u.sparse == nil { u.sparse = map[uint64]unmarshalFieldInfo{} } u.sparse[uint64(tag)] = i } // fieldUnmarshaler returns an unmarshaler for the given field. func fieldUnmarshaler(f *reflect.StructField) unmarshaler { if f.Type.Kind() == reflect.Map { return makeUnmarshalMap(f) } return typeUnmarshaler(f.Type, f.Tag.Get("protobuf")) } // typeUnmarshaler returns an unmarshaler for the given field type / field tag pair. func typeUnmarshaler(t reflect.Type, tags string) unmarshaler { tagArray := strings.Split(tags, ",") encoding := tagArray[0] name := "unknown" ctype := false isTime := false isDuration := false isWktPointer := false proto3 := false validateUTF8 := true for _, tag := range tagArray[3:] { if strings.HasPrefix(tag, "name=") { name = tag[5:] } if tag == "proto3" { proto3 = true } if strings.HasPrefix(tag, "customtype=") { ctype = true } if tag == "stdtime" { isTime = true } if tag == "stdduration" { isDuration = true } if tag == "wktptr" { isWktPointer = true } } validateUTF8 = validateUTF8 && proto3 // Figure out packaging (pointer, slice, or both) slice := false pointer := false if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 { slice = true t = t.Elem() } if t.Kind() == reflect.Ptr { pointer = true t = t.Elem() } if ctype { if reflect.PtrTo(t).Implements(customType) { if slice { return makeUnmarshalCustomSlice(getUnmarshalInfo(t), name) } if pointer { return makeUnmarshalCustomPtr(getUnmarshalInfo(t), name) } return makeUnmarshalCustom(getUnmarshalInfo(t), name) } else { panic(fmt.Sprintf("custom type: type: %v, does not implement the proto.custom interface", t)) } } if isTime { if pointer { if slice { return makeUnmarshalTimePtrSlice(getUnmarshalInfo(t), name) } return makeUnmarshalTimePtr(getUnmarshalInfo(t), name) } if slice { return makeUnmarshalTimeSlice(getUnmarshalInfo(t), name) } return makeUnmarshalTime(getUnmarshalInfo(t), name) } if isDuration { if pointer { if slice { return makeUnmarshalDurationPtrSlice(getUnmarshalInfo(t), name) } return makeUnmarshalDurationPtr(getUnmarshalInfo(t), name) } if slice { return makeUnmarshalDurationSlice(getUnmarshalInfo(t), name) } return makeUnmarshalDuration(getUnmarshalInfo(t), name) } if isWktPointer { switch t.Kind() { case reflect.Float64: if pointer { if slice { return makeStdDoubleValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name) } return makeStdDoubleValuePtrUnmarshaler(getUnmarshalInfo(t), name) } if slice { return makeStdDoubleValueSliceUnmarshaler(getUnmarshalInfo(t), name) } return makeStdDoubleValueUnmarshaler(getUnmarshalInfo(t), name) case reflect.Float32: if pointer { if slice { return makeStdFloatValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name) } return makeStdFloatValuePtrUnmarshaler(getUnmarshalInfo(t), name) } if slice { return makeStdFloatValueSliceUnmarshaler(getUnmarshalInfo(t), name) } return makeStdFloatValueUnmarshaler(getUnmarshalInfo(t), name) case reflect.Int64: if pointer { if slice { return makeStdInt64ValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name) } return makeStdInt64ValuePtrUnmarshaler(getUnmarshalInfo(t), name) } if slice { return makeStdInt64ValueSliceUnmarshaler(getUnmarshalInfo(t), name) } return makeStdInt64ValueUnmarshaler(getUnmarshalInfo(t), name) case reflect.Uint64: if pointer { if slice { return makeStdUInt64ValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name) } return makeStdUInt64ValuePtrUnmarshaler(getUnmarshalInfo(t), name) } if slice { return makeStdUInt64ValueSliceUnmarshaler(getUnmarshalInfo(t), name) } return makeStdUInt64ValueUnmarshaler(getUnmarshalInfo(t), name) case reflect.Int32: if pointer { if slice { return makeStdInt32ValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name) } return makeStdInt32ValuePtrUnmarshaler(getUnmarshalInfo(t), name) } if slice { return makeStdInt32ValueSliceUnmarshaler(getUnmarshalInfo(t), name) } return makeStdInt32ValueUnmarshaler(getUnmarshalInfo(t), name) case reflect.Uint32: if pointer { if slice { return makeStdUInt32ValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name) } return makeStdUInt32ValuePtrUnmarshaler(getUnmarshalInfo(t), name) } if slice { return makeStdUInt32ValueSliceUnmarshaler(getUnmarshalInfo(t), name) } return makeStdUInt32ValueUnmarshaler(getUnmarshalInfo(t), name) case reflect.Bool: if pointer { if slice { return makeStdBoolValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name) } return makeStdBoolValuePtrUnmarshaler(getUnmarshalInfo(t), name) } if slice { return makeStdBoolValueSliceUnmarshaler(getUnmarshalInfo(t), name) } return makeStdBoolValueUnmarshaler(getUnmarshalInfo(t), name) case reflect.String: if pointer { if slice { return makeStdStringValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name) } return makeStdStringValuePtrUnmarshaler(getUnmarshalInfo(t), name) } if slice { return makeStdStringValueSliceUnmarshaler(getUnmarshalInfo(t), name) } return makeStdStringValueUnmarshaler(getUnmarshalInfo(t), name) case uint8SliceType: if pointer { if slice { return makeStdBytesValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name) } return makeStdBytesValuePtrUnmarshaler(getUnmarshalInfo(t), name) } if slice { return makeStdBytesValueSliceUnmarshaler(getUnmarshalInfo(t), name) } return makeStdBytesValueUnmarshaler(getUnmarshalInfo(t), name) default: panic(fmt.Sprintf("unknown wktpointer type %#v", t)) } } // We'll never have both pointer and slice for basic types. if pointer && slice && t.Kind() != reflect.Struct { panic("both pointer and slice for basic type in " + t.Name()) } switch t.Kind() { case reflect.Bool: if pointer { return unmarshalBoolPtr } if slice { return unmarshalBoolSlice } return unmarshalBoolValue case reflect.Int32: switch encoding { case "fixed32": if pointer { return unmarshalFixedS32Ptr } if slice { return unmarshalFixedS32Slice } return unmarshalFixedS32Value case "varint": // this could be int32 or enum if pointer { return unmarshalInt32Ptr } if slice { return unmarshalInt32Slice } return unmarshalInt32Value case "zigzag32": if pointer { return unmarshalSint32Ptr } if slice { return unmarshalSint32Slice } return unmarshalSint32Value } case reflect.Int64: switch encoding { case "fixed64": if pointer { return unmarshalFixedS64Ptr } if slice { return unmarshalFixedS64Slice } return unmarshalFixedS64Value case "varint": if pointer { return unmarshalInt64Ptr } if slice { return unmarshalInt64Slice } return unmarshalInt64Value case "zigzag64": if pointer { return unmarshalSint64Ptr } if slice { return unmarshalSint64Slice } return unmarshalSint64Value } case reflect.Uint32: switch encoding { case "fixed32": if pointer { return unmarshalFixed32Ptr } if slice { return unmarshalFixed32Slice } return unmarshalFixed32Value case "varint": if pointer { return unmarshalUint32Ptr } if slice { return unmarshalUint32Slice } return unmarshalUint32Value } case reflect.Uint64: switch encoding { case "fixed64": if pointer { return unmarshalFixed64Ptr } if slice { return unmarshalFixed64Slice } return unmarshalFixed64Value case "varint": if pointer { return unmarshalUint64Ptr } if slice { return unmarshalUint64Slice } return unmarshalUint64Value } case reflect.Float32: if pointer { return unmarshalFloat32Ptr } if slice { return unmarshalFloat32Slice } return unmarshalFloat32Value case reflect.Float64: if pointer { return unmarshalFloat64Ptr } if slice { return unmarshalFloat64Slice } return unmarshalFloat64Value case reflect.Map: panic("map type in typeUnmarshaler in " + t.Name()) case reflect.Slice: if pointer { panic("bad pointer in slice case in " + t.Name()) } if slice { return unmarshalBytesSlice } return unmarshalBytesValue case reflect.String: if validateUTF8 { if pointer { return unmarshalUTF8StringPtr } if slice { return unmarshalUTF8StringSlice } return unmarshalUTF8StringValue } if pointer { return unmarshalStringPtr } if slice { return unmarshalStringSlice } return unmarshalStringValue case reflect.Struct: // message or group field if !pointer { switch encoding { case "bytes": if slice { return makeUnmarshalMessageSlice(getUnmarshalInfo(t), name) } return makeUnmarshalMessage(getUnmarshalInfo(t), name) } } switch encoding { case "bytes": if slice { return makeUnmarshalMessageSlicePtr(getUnmarshalInfo(t), name) } return makeUnmarshalMessagePtr(getUnmarshalInfo(t), name) case "group": if slice { return makeUnmarshalGroupSlicePtr(getUnmarshalInfo(t), name) } return makeUnmarshalGroupPtr(getUnmarshalInfo(t), name) } } panic(fmt.Sprintf("unmarshaler not found type:%s encoding:%s", t, encoding)) } // Below are all the unmarshalers for individual fields of various types. func unmarshalInt64Value(b []byte, f pointer, w int) ([]byte, error) { if w != WireVarint { return b, errInternalBadWireType } x, n := decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] v := int64(x) *f.toInt64() = v return b, nil } func unmarshalInt64Ptr(b []byte, f pointer, w int) ([]byte, error) { if w != WireVarint { return b, errInternalBadWireType } x, n := decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] v := int64(x) *f.toInt64Ptr() = &v return b, nil } func unmarshalInt64Slice(b []byte, f pointer, w int) ([]byte, error) { if w == WireBytes { // packed x, n := decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] if x > uint64(len(b)) { return nil, io.ErrUnexpectedEOF } res := b[x:] b = b[:x] for len(b) > 0 { x, n = decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] v := int64(x) s := f.toInt64Slice() *s = append(*s, v) } return res, nil } if w != WireVarint { return b, errInternalBadWireType } x, n := decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] v := int64(x) s := f.toInt64Slice() *s = append(*s, v) return b, nil } func unmarshalSint64Value(b []byte, f pointer, w int) ([]byte, error) { if w != WireVarint { return b, errInternalBadWireType } x, n := decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] v := int64(x>>1) ^ int64(x)<<63>>63 *f.toInt64() = v return b, nil } func unmarshalSint64Ptr(b []byte, f pointer, w int) ([]byte, error) { if w != WireVarint { return b, errInternalBadWireType } x, n := decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] v := int64(x>>1) ^ int64(x)<<63>>63 *f.toInt64Ptr() = &v return b, nil } func unmarshalSint64Slice(b []byte, f pointer, w int) ([]byte, error) { if w == WireBytes { // packed x, n := decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] if x > uint64(len(b)) { return nil, io.ErrUnexpectedEOF } res := b[x:] b = b[:x] for len(b) > 0 { x, n = decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] v := int64(x>>1) ^ int64(x)<<63>>63 s := f.toInt64Slice() *s = append(*s, v) } return res, nil } if w != WireVarint { return b, errInternalBadWireType } x, n := decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] v := int64(x>>1) ^ int64(x)<<63>>63 s := f.toInt64Slice() *s = append(*s, v) return b, nil } func unmarshalUint64Value(b []byte, f pointer, w int) ([]byte, error) { if w != WireVarint { return b, errInternalBadWireType } x, n := decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] v := uint64(x) *f.toUint64() = v return b, nil } func unmarshalUint64Ptr(b []byte, f pointer, w int) ([]byte, error) { if w != WireVarint { return b, errInternalBadWireType } x, n := decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] v := uint64(x) *f.toUint64Ptr() = &v return b, nil } func unmarshalUint64Slice(b []byte, f pointer, w int) ([]byte, error) { if w == WireBytes { // packed x, n := decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] if x > uint64(len(b)) { return nil, io.ErrUnexpectedEOF } res := b[x:] b = b[:x] for len(b) > 0 { x, n = decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] v := uint64(x) s := f.toUint64Slice() *s = append(*s, v) } return res, nil } if w != WireVarint { return b, errInternalBadWireType } x, n := decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] v := uint64(x) s := f.toUint64Slice() *s = append(*s, v) return b, nil } func unmarshalInt32Value(b []byte, f pointer, w int) ([]byte, error) { if w != WireVarint { return b, errInternalBadWireType } x, n := decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] v := int32(x) *f.toInt32() = v return b, nil } func unmarshalInt32Ptr(b []byte, f pointer, w int) ([]byte, error) { if w != WireVarint { return b, errInternalBadWireType } x, n := decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] v := int32(x) f.setInt32Ptr(v) return b, nil } func unmarshalInt32Slice(b []byte, f pointer, w int) ([]byte, error) { if w == WireBytes { // packed x, n := decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] if x > uint64(len(b)) { return nil, io.ErrUnexpectedEOF } res := b[x:] b = b[:x] for len(b) > 0 { x, n = decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] v := int32(x) f.appendInt32Slice(v) } return res, nil } if w != WireVarint { return b, errInternalBadWireType } x, n := decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] v := int32(x) f.appendInt32Slice(v) return b, nil } func unmarshalSint32Value(b []byte, f pointer, w int) ([]byte, error) { if w != WireVarint { return b, errInternalBadWireType } x, n := decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] v := int32(x>>1) ^ int32(x)<<31>>31 *f.toInt32() = v return b, nil } func unmarshalSint32Ptr(b []byte, f pointer, w int) ([]byte, error) { if w != WireVarint { return b, errInternalBadWireType } x, n := decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] v := int32(x>>1) ^ int32(x)<<31>>31 f.setInt32Ptr(v) return b, nil } func unmarshalSint32Slice(b []byte, f pointer, w int) ([]byte, error) { if w == WireBytes { // packed x, n := decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] if x > uint64(len(b)) { return nil, io.ErrUnexpectedEOF } res := b[x:] b = b[:x] for len(b) > 0 { x, n = decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] v := int32(x>>1) ^ int32(x)<<31>>31 f.appendInt32Slice(v) } return res, nil } if w != WireVarint { return b, errInternalBadWireType } x, n := decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] v := int32(x>>1) ^ int32(x)<<31>>31 f.appendInt32Slice(v) return b, nil } func unmarshalUint32Value(b []byte, f pointer, w int) ([]byte, error) { if w != WireVarint { return b, errInternalBadWireType } x, n := decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] v := uint32(x) *f.toUint32() = v return b, nil } func unmarshalUint32Ptr(b []byte, f pointer, w int) ([]byte, error) { if w != WireVarint { return b, errInternalBadWireType } x, n := decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] v := uint32(x) *f.toUint32Ptr() = &v return b, nil } func unmarshalUint32Slice(b []byte, f pointer, w int) ([]byte, error) { if w == WireBytes { // packed x, n := decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] if x > uint64(len(b)) { return nil, io.ErrUnexpectedEOF } res := b[x:] b = b[:x] for len(b) > 0 { x, n = decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] v := uint32(x) s := f.toUint32Slice() *s = append(*s, v) } return res, nil } if w != WireVarint { return b, errInternalBadWireType } x, n := decodeVarint(b) if n == 0 { return nil, io.ErrUnexpectedEOF } b = b[n:] v := uint32(x) s := f.toUint32Slice() *s = append(*s, v) return b, nil } func unmarshalFixed64Value(b []byte, f pointer, w int) ([]byte, error) { if w != WireFixed64 { return b, errInternalBadWireType } if len(b) < 8 { return nil, io.ErrUnexpectedEOF } v := uint64(b[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 *f.toUint64() = v return b[8:], nil } func unmarshalFixed64Ptr(b []byte, f pointer, w int) ([]byte, error) { if w != WireFixed64 { return b, errInternalBadWireType } if len(b) < 8 { return nil, io.ErrUnexpectedEOF }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gogo/protobuf/proto/lib_gogo.go
vendor/github.com/gogo/protobuf/proto/lib_gogo.go
// Protocol Buffers for Go with Gadgets // // Copyright (c) 2013, The GoGo Authors. All rights reserved. // http://github.com/gogo/protobuf // // 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. // // 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. package proto import ( "encoding/json" "strconv" ) type Sizer interface { Size() int } type ProtoSizer interface { ProtoSize() int } func MarshalJSONEnum(m map[int32]string, value int32) ([]byte, error) { s, ok := m[value] if !ok { s = strconv.Itoa(int(value)) } return json.Marshal(s) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gogo/protobuf/proto/properties_gogo.go
vendor/github.com/gogo/protobuf/proto/properties_gogo.go
// Protocol Buffers for Go with Gadgets // // Copyright (c) 2018, The GoGo Authors. All rights reserved. // http://github.com/gogo/protobuf // // 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. // // 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. package proto import ( "reflect" ) var sizerType = reflect.TypeOf((*Sizer)(nil)).Elem() var protosizerType = reflect.TypeOf((*ProtoSizer)(nil)).Elem()
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gogo/protobuf/proto/message_set.go
vendor/github.com/gogo/protobuf/proto/message_set.go
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // 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. package proto /* * Support for message sets. */ import ( "errors" ) // errNoMessageTypeID occurs when a protocol buffer does not have a message type ID. // A message type ID is required for storing a protocol buffer in a message set. var errNoMessageTypeID = errors.New("proto does not have a message type ID") // The first two types (_MessageSet_Item and messageSet) // model what the protocol compiler produces for the following protocol message: // message MessageSet { // repeated group Item = 1 { // required int32 type_id = 2; // required string message = 3; // }; // } // That is the MessageSet wire format. We can't use a proto to generate these // because that would introduce a circular dependency between it and this package. type _MessageSet_Item struct { TypeId *int32 `protobuf:"varint,2,req,name=type_id"` Message []byte `protobuf:"bytes,3,req,name=message"` } type messageSet struct { Item []*_MessageSet_Item `protobuf:"group,1,rep"` XXX_unrecognized []byte // TODO: caching? } // Make sure messageSet is a Message. var _ Message = (*messageSet)(nil) // messageTypeIder is an interface satisfied by a protocol buffer type // that may be stored in a MessageSet. type messageTypeIder interface { MessageTypeId() int32 } func (ms *messageSet) find(pb Message) *_MessageSet_Item { mti, ok := pb.(messageTypeIder) if !ok { return nil } id := mti.MessageTypeId() for _, item := range ms.Item { if *item.TypeId == id { return item } } return nil } func (ms *messageSet) Has(pb Message) bool { return ms.find(pb) != nil } func (ms *messageSet) Unmarshal(pb Message) error { if item := ms.find(pb); item != nil { return Unmarshal(item.Message, pb) } if _, ok := pb.(messageTypeIder); !ok { return errNoMessageTypeID } return nil // TODO: return error instead? } func (ms *messageSet) Marshal(pb Message) error { msg, err := Marshal(pb) if err != nil { return err } if item := ms.find(pb); item != nil { // reuse existing item item.Message = msg return nil } mti, ok := pb.(messageTypeIder) if !ok { return errNoMessageTypeID } mtid := mti.MessageTypeId() ms.Item = append(ms.Item, &_MessageSet_Item{ TypeId: &mtid, Message: msg, }) return nil } func (ms *messageSet) Reset() { *ms = messageSet{} } func (ms *messageSet) String() string { return CompactTextString(ms) } func (*messageSet) ProtoMessage() {} // Support for the message_set_wire_format message option. func skipVarint(buf []byte) []byte { i := 0 for ; buf[i]&0x80 != 0; i++ { } return buf[i+1:] } // unmarshalMessageSet decodes the extension map encoded in buf in the message set wire format. // It is called by Unmarshal methods on protocol buffer messages with the message_set_wire_format option. func unmarshalMessageSet(buf []byte, exts interface{}) error { var m map[int32]Extension switch exts := exts.(type) { case *XXX_InternalExtensions: m = exts.extensionsWrite() case map[int32]Extension: m = exts default: return errors.New("proto: not an extension map") } ms := new(messageSet) if err := Unmarshal(buf, ms); err != nil { return err } for _, item := range ms.Item { id := *item.TypeId msg := item.Message // Restore wire type and field number varint, plus length varint. // Be careful to preserve duplicate items. b := EncodeVarint(uint64(id)<<3 | WireBytes) if ext, ok := m[id]; ok { // Existing data; rip off the tag and length varint // so we join the new data correctly. // We can assume that ext.enc is set because we are unmarshaling. o := ext.enc[len(b):] // skip wire type and field number _, n := DecodeVarint(o) // calculate length of length varint o = o[n:] // skip length varint msg = append(o, msg...) // join old data and new data } b = append(b, EncodeVarint(uint64(len(msg)))...) b = append(b, msg...) m[id] = Extension{enc: b} } return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gogo/protobuf/proto/encode_gogo.go
vendor/github.com/gogo/protobuf/proto/encode_gogo.go
// Protocol Buffers for Go with Gadgets // // Copyright (c) 2013, The GoGo Authors. All rights reserved. // http://github.com/gogo/protobuf // // 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. // // 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. package proto func NewRequiredNotSetError(field string) *RequiredNotSetError { return &RequiredNotSetError{field} }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gogo/protobuf/proto/equal.go
vendor/github.com/gogo/protobuf/proto/equal.go
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2011 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // 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. // Protocol buffer comparison. package proto import ( "bytes" "log" "reflect" "strings" ) /* Equal returns true iff protocol buffers a and b are equal. The arguments must both be pointers to protocol buffer structs. Equality is defined in this way: - Two messages are equal iff they are the same type, corresponding fields are equal, unknown field sets are equal, and extensions sets are equal. - Two set scalar fields are equal iff their values are equal. If the fields are of a floating-point type, remember that NaN != x for all x, including NaN. If the message is defined in a proto3 .proto file, fields are not "set"; specifically, zero length proto3 "bytes" fields are equal (nil == {}). - Two repeated fields are equal iff their lengths are the same, and their corresponding elements are equal. Note a "bytes" field, although represented by []byte, is not a repeated field and the rule for the scalar fields described above applies. - Two unset fields are equal. - Two unknown field sets are equal if their current encoded state is equal. - Two extension sets are equal iff they have corresponding elements that are pairwise equal. - Two map fields are equal iff their lengths are the same, and they contain the same set of elements. Zero-length map fields are equal. - Every other combination of things are not equal. The return value is undefined if a and b are not protocol buffers. */ func Equal(a, b Message) bool { if a == nil || b == nil { return a == b } v1, v2 := reflect.ValueOf(a), reflect.ValueOf(b) if v1.Type() != v2.Type() { return false } if v1.Kind() == reflect.Ptr { if v1.IsNil() { return v2.IsNil() } if v2.IsNil() { return false } v1, v2 = v1.Elem(), v2.Elem() } if v1.Kind() != reflect.Struct { return false } return equalStruct(v1, v2) } // v1 and v2 are known to have the same type. func equalStruct(v1, v2 reflect.Value) bool { sprop := GetProperties(v1.Type()) for i := 0; i < v1.NumField(); i++ { f := v1.Type().Field(i) if strings.HasPrefix(f.Name, "XXX_") { continue } f1, f2 := v1.Field(i), v2.Field(i) if f.Type.Kind() == reflect.Ptr { if n1, n2 := f1.IsNil(), f2.IsNil(); n1 && n2 { // both unset continue } else if n1 != n2 { // set/unset mismatch return false } f1, f2 = f1.Elem(), f2.Elem() } if !equalAny(f1, f2, sprop.Prop[i]) { return false } } if em1 := v1.FieldByName("XXX_InternalExtensions"); em1.IsValid() { em2 := v2.FieldByName("XXX_InternalExtensions") if !equalExtensions(v1.Type(), em1.Interface().(XXX_InternalExtensions), em2.Interface().(XXX_InternalExtensions)) { return false } } if em1 := v1.FieldByName("XXX_extensions"); em1.IsValid() { em2 := v2.FieldByName("XXX_extensions") if !equalExtMap(v1.Type(), em1.Interface().(map[int32]Extension), em2.Interface().(map[int32]Extension)) { return false } } uf := v1.FieldByName("XXX_unrecognized") if !uf.IsValid() { return true } u1 := uf.Bytes() u2 := v2.FieldByName("XXX_unrecognized").Bytes() return bytes.Equal(u1, u2) } // v1 and v2 are known to have the same type. // prop may be nil. func equalAny(v1, v2 reflect.Value, prop *Properties) bool { if v1.Type() == protoMessageType { m1, _ := v1.Interface().(Message) m2, _ := v2.Interface().(Message) return Equal(m1, m2) } switch v1.Kind() { case reflect.Bool: return v1.Bool() == v2.Bool() case reflect.Float32, reflect.Float64: return v1.Float() == v2.Float() case reflect.Int32, reflect.Int64: return v1.Int() == v2.Int() case reflect.Interface: // Probably a oneof field; compare the inner values. n1, n2 := v1.IsNil(), v2.IsNil() if n1 || n2 { return n1 == n2 } e1, e2 := v1.Elem(), v2.Elem() if e1.Type() != e2.Type() { return false } return equalAny(e1, e2, nil) case reflect.Map: if v1.Len() != v2.Len() { return false } for _, key := range v1.MapKeys() { val2 := v2.MapIndex(key) if !val2.IsValid() { // This key was not found in the second map. return false } if !equalAny(v1.MapIndex(key), val2, nil) { return false } } return true case reflect.Ptr: // Maps may have nil values in them, so check for nil. if v1.IsNil() && v2.IsNil() { return true } if v1.IsNil() != v2.IsNil() { return false } return equalAny(v1.Elem(), v2.Elem(), prop) case reflect.Slice: if v1.Type().Elem().Kind() == reflect.Uint8 { // short circuit: []byte // Edge case: if this is in a proto3 message, a zero length // bytes field is considered the zero value. if prop != nil && prop.proto3 && v1.Len() == 0 && v2.Len() == 0 { return true } if v1.IsNil() != v2.IsNil() { return false } return bytes.Equal(v1.Interface().([]byte), v2.Interface().([]byte)) } if v1.Len() != v2.Len() { return false } for i := 0; i < v1.Len(); i++ { if !equalAny(v1.Index(i), v2.Index(i), prop) { return false } } return true case reflect.String: return v1.Interface().(string) == v2.Interface().(string) case reflect.Struct: return equalStruct(v1, v2) case reflect.Uint32, reflect.Uint64: return v1.Uint() == v2.Uint() } // unknown type, so not a protocol buffer log.Printf("proto: don't know how to compare %v", v1) return false } // base is the struct type that the extensions are based on. // x1 and x2 are InternalExtensions. func equalExtensions(base reflect.Type, x1, x2 XXX_InternalExtensions) bool { em1, _ := x1.extensionsRead() em2, _ := x2.extensionsRead() return equalExtMap(base, em1, em2) } func equalExtMap(base reflect.Type, em1, em2 map[int32]Extension) bool { if len(em1) != len(em2) { return false } for extNum, e1 := range em1 { e2, ok := em2[extNum] if !ok { return false } m1, m2 := e1.value, e2.value if m1 == nil && m2 == nil { // Both have only encoded form. if bytes.Equal(e1.enc, e2.enc) { continue } // The bytes are different, but the extensions might still be // equal. We need to decode them to compare. } if m1 != nil && m2 != nil { // Both are unencoded. if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) { return false } continue } // At least one is encoded. To do a semantically correct comparison // we need to unmarshal them first. var desc *ExtensionDesc if m := extensionMaps[base]; m != nil { desc = m[extNum] } if desc == nil { // If both have only encoded form and the bytes are the same, // it is handled above. We get here when the bytes are different. // We don't know how to decode it, so just compare them as byte // slices. log.Printf("proto: don't know how to compare extension %d of %v", extNum, base) return false } var err error if m1 == nil { m1, err = decodeExtension(e1.enc, desc) } if m2 == nil && err == nil { m2, err = decodeExtension(e2.enc, desc) } if err != nil { // The encoded form is invalid. log.Printf("proto: badly encoded extension %d of %v: %v", extNum, base, err) return false } if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) { 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/vendor/github.com/gogo/protobuf/proto/pointer_unsafe.go
vendor/github.com/gogo/protobuf/proto/pointer_unsafe.go
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2012 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // 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. // +build !purego,!appengine,!js // This file contains the implementation of the proto field accesses using package unsafe. package proto import ( "reflect" "sync/atomic" "unsafe" ) const unsafeAllowed = true // A field identifies a field in a struct, accessible from a pointer. // In this implementation, a field is identified by its byte offset from the start of the struct. type field uintptr // toField returns a field equivalent to the given reflect field. func toField(f *reflect.StructField) field { return field(f.Offset) } // invalidField is an invalid field identifier. const invalidField = ^field(0) // zeroField is a noop when calling pointer.offset. const zeroField = field(0) // IsValid reports whether the field identifier is valid. func (f field) IsValid() bool { return f != invalidField } // The pointer type below is for the new table-driven encoder/decoder. // The implementation here uses unsafe.Pointer to create a generic pointer. // In pointer_reflect.go we use reflect instead of unsafe to implement // the same (but slower) interface. type pointer struct { p unsafe.Pointer } // size of pointer var ptrSize = unsafe.Sizeof(uintptr(0)) // toPointer converts an interface of pointer type to a pointer // that points to the same target. func toPointer(i *Message) pointer { // Super-tricky - read pointer out of data word of interface value. // Saves ~25ns over the equivalent: // return valToPointer(reflect.ValueOf(*i)) return pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]} } // toAddrPointer converts an interface to a pointer that points to // the interface data. func toAddrPointer(i *interface{}, isptr bool) pointer { // Super-tricky - read or get the address of data word of interface value. if isptr { // The interface is of pointer type, thus it is a direct interface. // The data word is the pointer data itself. We take its address. return pointer{p: unsafe.Pointer(uintptr(unsafe.Pointer(i)) + ptrSize)} } // The interface is not of pointer type. The data word is the pointer // to the data. return pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]} } // valToPointer converts v to a pointer. v must be of pointer type. func valToPointer(v reflect.Value) pointer { return pointer{p: unsafe.Pointer(v.Pointer())} } // offset converts from a pointer to a structure to a pointer to // one of its fields. func (p pointer) offset(f field) pointer { // For safety, we should panic if !f.IsValid, however calling panic causes // this to no longer be inlineable, which is a serious performance cost. /* if !f.IsValid() { panic("invalid field") } */ return pointer{p: unsafe.Pointer(uintptr(p.p) + uintptr(f))} } func (p pointer) isNil() bool { return p.p == nil } func (p pointer) toInt64() *int64 { return (*int64)(p.p) } func (p pointer) toInt64Ptr() **int64 { return (**int64)(p.p) } func (p pointer) toInt64Slice() *[]int64 { return (*[]int64)(p.p) } func (p pointer) toInt32() *int32 { return (*int32)(p.p) } // See pointer_reflect.go for why toInt32Ptr/Slice doesn't exist. /* func (p pointer) toInt32Ptr() **int32 { return (**int32)(p.p) } func (p pointer) toInt32Slice() *[]int32 { return (*[]int32)(p.p) } */ func (p pointer) getInt32Ptr() *int32 { return *(**int32)(p.p) } func (p pointer) setInt32Ptr(v int32) { *(**int32)(p.p) = &v } // getInt32Slice loads a []int32 from p. // The value returned is aliased with the original slice. // This behavior differs from the implementation in pointer_reflect.go. func (p pointer) getInt32Slice() []int32 { return *(*[]int32)(p.p) } // setInt32Slice stores a []int32 to p. // The value set is aliased with the input slice. // This behavior differs from the implementation in pointer_reflect.go. func (p pointer) setInt32Slice(v []int32) { *(*[]int32)(p.p) = v } // TODO: Can we get rid of appendInt32Slice and use setInt32Slice instead? func (p pointer) appendInt32Slice(v int32) { s := (*[]int32)(p.p) *s = append(*s, v) } func (p pointer) toUint64() *uint64 { return (*uint64)(p.p) } func (p pointer) toUint64Ptr() **uint64 { return (**uint64)(p.p) } func (p pointer) toUint64Slice() *[]uint64 { return (*[]uint64)(p.p) } func (p pointer) toUint32() *uint32 { return (*uint32)(p.p) } func (p pointer) toUint32Ptr() **uint32 { return (**uint32)(p.p) } func (p pointer) toUint32Slice() *[]uint32 { return (*[]uint32)(p.p) } func (p pointer) toBool() *bool { return (*bool)(p.p) } func (p pointer) toBoolPtr() **bool { return (**bool)(p.p) } func (p pointer) toBoolSlice() *[]bool { return (*[]bool)(p.p) } func (p pointer) toFloat64() *float64 { return (*float64)(p.p) } func (p pointer) toFloat64Ptr() **float64 { return (**float64)(p.p) } func (p pointer) toFloat64Slice() *[]float64 { return (*[]float64)(p.p) } func (p pointer) toFloat32() *float32 { return (*float32)(p.p) } func (p pointer) toFloat32Ptr() **float32 { return (**float32)(p.p) } func (p pointer) toFloat32Slice() *[]float32 { return (*[]float32)(p.p) } func (p pointer) toString() *string { return (*string)(p.p) } func (p pointer) toStringPtr() **string { return (**string)(p.p) } func (p pointer) toStringSlice() *[]string { return (*[]string)(p.p) } func (p pointer) toBytes() *[]byte { return (*[]byte)(p.p) } func (p pointer) toBytesSlice() *[][]byte { return (*[][]byte)(p.p) } func (p pointer) toExtensions() *XXX_InternalExtensions { return (*XXX_InternalExtensions)(p.p) } func (p pointer) toOldExtensions() *map[int32]Extension { return (*map[int32]Extension)(p.p) } // getPointerSlice loads []*T from p as a []pointer. // The value returned is aliased with the original slice. // This behavior differs from the implementation in pointer_reflect.go. func (p pointer) getPointerSlice() []pointer { // Super-tricky - p should point to a []*T where T is a // message type. We load it as []pointer. return *(*[]pointer)(p.p) } // setPointerSlice stores []pointer into p as a []*T. // The value set is aliased with the input slice. // This behavior differs from the implementation in pointer_reflect.go. func (p pointer) setPointerSlice(v []pointer) { // Super-tricky - p should point to a []*T where T is a // message type. We store it as []pointer. *(*[]pointer)(p.p) = v } // getPointer loads the pointer at p and returns it. func (p pointer) getPointer() pointer { return pointer{p: *(*unsafe.Pointer)(p.p)} } // setPointer stores the pointer q at p. func (p pointer) setPointer(q pointer) { *(*unsafe.Pointer)(p.p) = q.p } // append q to the slice pointed to by p. func (p pointer) appendPointer(q pointer) { s := (*[]unsafe.Pointer)(p.p) *s = append(*s, q.p) } // getInterfacePointer returns a pointer that points to the // interface data of the interface pointed by p. func (p pointer) getInterfacePointer() pointer { // Super-tricky - read pointer out of data word of interface value. return pointer{p: (*(*[2]unsafe.Pointer)(p.p))[1]} } // asPointerTo returns a reflect.Value that is a pointer to an // object of type t stored at p. func (p pointer) asPointerTo(t reflect.Type) reflect.Value { return reflect.NewAt(t, p.p) } func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo { return (*unmarshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) } func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) { atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) } func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo { return (*marshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) } func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) { atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) } func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo { return (*mergeInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) } func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) { atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) } func atomicLoadDiscardInfo(p **discardInfo) *discardInfo { return (*discardInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) } func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) { atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gogo/protobuf/proto/table_merge.go
vendor/github.com/gogo/protobuf/proto/table_merge.go
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2016 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // 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. package proto import ( "fmt" "reflect" "strings" "sync" "sync/atomic" ) // Merge merges the src message into dst. // This assumes that dst and src of the same type and are non-nil. func (a *InternalMessageInfo) Merge(dst, src Message) { mi := atomicLoadMergeInfo(&a.merge) if mi == nil { mi = getMergeInfo(reflect.TypeOf(dst).Elem()) atomicStoreMergeInfo(&a.merge, mi) } mi.merge(toPointer(&dst), toPointer(&src)) } type mergeInfo struct { typ reflect.Type initialized int32 // 0: only typ is valid, 1: everything is valid lock sync.Mutex fields []mergeFieldInfo unrecognized field // Offset of XXX_unrecognized } type mergeFieldInfo struct { field field // Offset of field, guaranteed to be valid // isPointer reports whether the value in the field is a pointer. // This is true for the following situations: // * Pointer to struct // * Pointer to basic type (proto2 only) // * Slice (first value in slice header is a pointer) // * String (first value in string header is a pointer) isPointer bool // basicWidth reports the width of the field assuming that it is directly // embedded in the struct (as is the case for basic types in proto3). // The possible values are: // 0: invalid // 1: bool // 4: int32, uint32, float32 // 8: int64, uint64, float64 basicWidth int // Where dst and src are pointers to the types being merged. merge func(dst, src pointer) } var ( mergeInfoMap = map[reflect.Type]*mergeInfo{} mergeInfoLock sync.Mutex ) func getMergeInfo(t reflect.Type) *mergeInfo { mergeInfoLock.Lock() defer mergeInfoLock.Unlock() mi := mergeInfoMap[t] if mi == nil { mi = &mergeInfo{typ: t} mergeInfoMap[t] = mi } return mi } // merge merges src into dst assuming they are both of type *mi.typ. func (mi *mergeInfo) merge(dst, src pointer) { if dst.isNil() { panic("proto: nil destination") } if src.isNil() { return // Nothing to do. } if atomic.LoadInt32(&mi.initialized) == 0 { mi.computeMergeInfo() } for _, fi := range mi.fields { sfp := src.offset(fi.field) // As an optimization, we can avoid the merge function call cost // if we know for sure that the source will have no effect // by checking if it is the zero value. if unsafeAllowed { if fi.isPointer && sfp.getPointer().isNil() { // Could be slice or string continue } if fi.basicWidth > 0 { switch { case fi.basicWidth == 1 && !*sfp.toBool(): continue case fi.basicWidth == 4 && *sfp.toUint32() == 0: continue case fi.basicWidth == 8 && *sfp.toUint64() == 0: continue } } } dfp := dst.offset(fi.field) fi.merge(dfp, sfp) } // TODO: Make this faster? out := dst.asPointerTo(mi.typ).Elem() in := src.asPointerTo(mi.typ).Elem() if emIn, err := extendable(in.Addr().Interface()); err == nil { emOut, _ := extendable(out.Addr().Interface()) mIn, muIn := emIn.extensionsRead() if mIn != nil { mOut := emOut.extensionsWrite() muIn.Lock() mergeExtension(mOut, mIn) muIn.Unlock() } } if mi.unrecognized.IsValid() { if b := *src.offset(mi.unrecognized).toBytes(); len(b) > 0 { *dst.offset(mi.unrecognized).toBytes() = append([]byte(nil), b...) } } } func (mi *mergeInfo) computeMergeInfo() { mi.lock.Lock() defer mi.lock.Unlock() if mi.initialized != 0 { return } t := mi.typ n := t.NumField() props := GetProperties(t) for i := 0; i < n; i++ { f := t.Field(i) if strings.HasPrefix(f.Name, "XXX_") { continue } mfi := mergeFieldInfo{field: toField(&f)} tf := f.Type // As an optimization, we can avoid the merge function call cost // if we know for sure that the source will have no effect // by checking if it is the zero value. if unsafeAllowed { switch tf.Kind() { case reflect.Ptr, reflect.Slice, reflect.String: // As a special case, we assume slices and strings are pointers // since we know that the first field in the SliceSlice or // StringHeader is a data pointer. mfi.isPointer = true case reflect.Bool: mfi.basicWidth = 1 case reflect.Int32, reflect.Uint32, reflect.Float32: mfi.basicWidth = 4 case reflect.Int64, reflect.Uint64, reflect.Float64: mfi.basicWidth = 8 } } // Unwrap tf to get at its most basic type. var isPointer, isSlice bool if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { isSlice = true tf = tf.Elem() } if tf.Kind() == reflect.Ptr { isPointer = true tf = tf.Elem() } if isPointer && isSlice && tf.Kind() != reflect.Struct { panic("both pointer and slice for basic type in " + tf.Name()) } switch tf.Kind() { case reflect.Int32: switch { case isSlice: // E.g., []int32 mfi.merge = func(dst, src pointer) { // NOTE: toInt32Slice is not defined (see pointer_reflect.go). /* sfsp := src.toInt32Slice() if *sfsp != nil { dfsp := dst.toInt32Slice() *dfsp = append(*dfsp, *sfsp...) if *dfsp == nil { *dfsp = []int64{} } } */ sfs := src.getInt32Slice() if sfs != nil { dfs := dst.getInt32Slice() dfs = append(dfs, sfs...) if dfs == nil { dfs = []int32{} } dst.setInt32Slice(dfs) } } case isPointer: // E.g., *int32 mfi.merge = func(dst, src pointer) { // NOTE: toInt32Ptr is not defined (see pointer_reflect.go). /* sfpp := src.toInt32Ptr() if *sfpp != nil { dfpp := dst.toInt32Ptr() if *dfpp == nil { *dfpp = Int32(**sfpp) } else { **dfpp = **sfpp } } */ sfp := src.getInt32Ptr() if sfp != nil { dfp := dst.getInt32Ptr() if dfp == nil { dst.setInt32Ptr(*sfp) } else { *dfp = *sfp } } } default: // E.g., int32 mfi.merge = func(dst, src pointer) { if v := *src.toInt32(); v != 0 { *dst.toInt32() = v } } } case reflect.Int64: switch { case isSlice: // E.g., []int64 mfi.merge = func(dst, src pointer) { sfsp := src.toInt64Slice() if *sfsp != nil { dfsp := dst.toInt64Slice() *dfsp = append(*dfsp, *sfsp...) if *dfsp == nil { *dfsp = []int64{} } } } case isPointer: // E.g., *int64 mfi.merge = func(dst, src pointer) { sfpp := src.toInt64Ptr() if *sfpp != nil { dfpp := dst.toInt64Ptr() if *dfpp == nil { *dfpp = Int64(**sfpp) } else { **dfpp = **sfpp } } } default: // E.g., int64 mfi.merge = func(dst, src pointer) { if v := *src.toInt64(); v != 0 { *dst.toInt64() = v } } } case reflect.Uint32: switch { case isSlice: // E.g., []uint32 mfi.merge = func(dst, src pointer) { sfsp := src.toUint32Slice() if *sfsp != nil { dfsp := dst.toUint32Slice() *dfsp = append(*dfsp, *sfsp...) if *dfsp == nil { *dfsp = []uint32{} } } } case isPointer: // E.g., *uint32 mfi.merge = func(dst, src pointer) { sfpp := src.toUint32Ptr() if *sfpp != nil { dfpp := dst.toUint32Ptr() if *dfpp == nil { *dfpp = Uint32(**sfpp) } else { **dfpp = **sfpp } } } default: // E.g., uint32 mfi.merge = func(dst, src pointer) { if v := *src.toUint32(); v != 0 { *dst.toUint32() = v } } } case reflect.Uint64: switch { case isSlice: // E.g., []uint64 mfi.merge = func(dst, src pointer) { sfsp := src.toUint64Slice() if *sfsp != nil { dfsp := dst.toUint64Slice() *dfsp = append(*dfsp, *sfsp...) if *dfsp == nil { *dfsp = []uint64{} } } } case isPointer: // E.g., *uint64 mfi.merge = func(dst, src pointer) { sfpp := src.toUint64Ptr() if *sfpp != nil { dfpp := dst.toUint64Ptr() if *dfpp == nil { *dfpp = Uint64(**sfpp) } else { **dfpp = **sfpp } } } default: // E.g., uint64 mfi.merge = func(dst, src pointer) { if v := *src.toUint64(); v != 0 { *dst.toUint64() = v } } } case reflect.Float32: switch { case isSlice: // E.g., []float32 mfi.merge = func(dst, src pointer) { sfsp := src.toFloat32Slice() if *sfsp != nil { dfsp := dst.toFloat32Slice() *dfsp = append(*dfsp, *sfsp...) if *dfsp == nil { *dfsp = []float32{} } } } case isPointer: // E.g., *float32 mfi.merge = func(dst, src pointer) { sfpp := src.toFloat32Ptr() if *sfpp != nil { dfpp := dst.toFloat32Ptr() if *dfpp == nil { *dfpp = Float32(**sfpp) } else { **dfpp = **sfpp } } } default: // E.g., float32 mfi.merge = func(dst, src pointer) { if v := *src.toFloat32(); v != 0 { *dst.toFloat32() = v } } } case reflect.Float64: switch { case isSlice: // E.g., []float64 mfi.merge = func(dst, src pointer) { sfsp := src.toFloat64Slice() if *sfsp != nil { dfsp := dst.toFloat64Slice() *dfsp = append(*dfsp, *sfsp...) if *dfsp == nil { *dfsp = []float64{} } } } case isPointer: // E.g., *float64 mfi.merge = func(dst, src pointer) { sfpp := src.toFloat64Ptr() if *sfpp != nil { dfpp := dst.toFloat64Ptr() if *dfpp == nil { *dfpp = Float64(**sfpp) } else { **dfpp = **sfpp } } } default: // E.g., float64 mfi.merge = func(dst, src pointer) { if v := *src.toFloat64(); v != 0 { *dst.toFloat64() = v } } } case reflect.Bool: switch { case isSlice: // E.g., []bool mfi.merge = func(dst, src pointer) { sfsp := src.toBoolSlice() if *sfsp != nil { dfsp := dst.toBoolSlice() *dfsp = append(*dfsp, *sfsp...) if *dfsp == nil { *dfsp = []bool{} } } } case isPointer: // E.g., *bool mfi.merge = func(dst, src pointer) { sfpp := src.toBoolPtr() if *sfpp != nil { dfpp := dst.toBoolPtr() if *dfpp == nil { *dfpp = Bool(**sfpp) } else { **dfpp = **sfpp } } } default: // E.g., bool mfi.merge = func(dst, src pointer) { if v := *src.toBool(); v { *dst.toBool() = v } } } case reflect.String: switch { case isSlice: // E.g., []string mfi.merge = func(dst, src pointer) { sfsp := src.toStringSlice() if *sfsp != nil { dfsp := dst.toStringSlice() *dfsp = append(*dfsp, *sfsp...) if *dfsp == nil { *dfsp = []string{} } } } case isPointer: // E.g., *string mfi.merge = func(dst, src pointer) { sfpp := src.toStringPtr() if *sfpp != nil { dfpp := dst.toStringPtr() if *dfpp == nil { *dfpp = String(**sfpp) } else { **dfpp = **sfpp } } } default: // E.g., string mfi.merge = func(dst, src pointer) { if v := *src.toString(); v != "" { *dst.toString() = v } } } case reflect.Slice: isProto3 := props.Prop[i].proto3 switch { case isPointer: panic("bad pointer in byte slice case in " + tf.Name()) case tf.Elem().Kind() != reflect.Uint8: panic("bad element kind in byte slice case in " + tf.Name()) case isSlice: // E.g., [][]byte mfi.merge = func(dst, src pointer) { sbsp := src.toBytesSlice() if *sbsp != nil { dbsp := dst.toBytesSlice() for _, sb := range *sbsp { if sb == nil { *dbsp = append(*dbsp, nil) } else { *dbsp = append(*dbsp, append([]byte{}, sb...)) } } if *dbsp == nil { *dbsp = [][]byte{} } } } default: // E.g., []byte mfi.merge = func(dst, src pointer) { sbp := src.toBytes() if *sbp != nil { dbp := dst.toBytes() if !isProto3 || len(*sbp) > 0 { *dbp = append([]byte{}, *sbp...) } } } } case reflect.Struct: switch { case isSlice && !isPointer: // E.g. []pb.T mergeInfo := getMergeInfo(tf) zero := reflect.Zero(tf) mfi.merge = func(dst, src pointer) { // TODO: Make this faster? dstsp := dst.asPointerTo(f.Type) dsts := dstsp.Elem() srcs := src.asPointerTo(f.Type).Elem() for i := 0; i < srcs.Len(); i++ { dsts = reflect.Append(dsts, zero) srcElement := srcs.Index(i).Addr() dstElement := dsts.Index(dsts.Len() - 1).Addr() mergeInfo.merge(valToPointer(dstElement), valToPointer(srcElement)) } if dsts.IsNil() { dsts = reflect.MakeSlice(f.Type, 0, 0) } dstsp.Elem().Set(dsts) } case !isPointer: mergeInfo := getMergeInfo(tf) mfi.merge = func(dst, src pointer) { mergeInfo.merge(dst, src) } case isSlice: // E.g., []*pb.T mergeInfo := getMergeInfo(tf) mfi.merge = func(dst, src pointer) { sps := src.getPointerSlice() if sps != nil { dps := dst.getPointerSlice() for _, sp := range sps { var dp pointer if !sp.isNil() { dp = valToPointer(reflect.New(tf)) mergeInfo.merge(dp, sp) } dps = append(dps, dp) } if dps == nil { dps = []pointer{} } dst.setPointerSlice(dps) } } default: // E.g., *pb.T mergeInfo := getMergeInfo(tf) mfi.merge = func(dst, src pointer) { sp := src.getPointer() if !sp.isNil() { dp := dst.getPointer() if dp.isNil() { dp = valToPointer(reflect.New(tf)) dst.setPointer(dp) } mergeInfo.merge(dp, sp) } } } case reflect.Map: switch { case isPointer || isSlice: panic("bad pointer or slice in map case in " + tf.Name()) default: // E.g., map[K]V mfi.merge = func(dst, src pointer) { sm := src.asPointerTo(tf).Elem() if sm.Len() == 0 { return } dm := dst.asPointerTo(tf).Elem() if dm.IsNil() { dm.Set(reflect.MakeMap(tf)) } switch tf.Elem().Kind() { case reflect.Ptr: // Proto struct (e.g., *T) for _, key := range sm.MapKeys() { val := sm.MapIndex(key) val = reflect.ValueOf(Clone(val.Interface().(Message))) dm.SetMapIndex(key, val) } case reflect.Slice: // E.g. Bytes type (e.g., []byte) for _, key := range sm.MapKeys() { val := sm.MapIndex(key) val = reflect.ValueOf(append([]byte{}, val.Bytes()...)) dm.SetMapIndex(key, val) } default: // Basic type (e.g., string) for _, key := range sm.MapKeys() { val := sm.MapIndex(key) dm.SetMapIndex(key, val) } } } } case reflect.Interface: // Must be oneof field. switch { case isPointer || isSlice: panic("bad pointer or slice in interface case in " + tf.Name()) default: // E.g., interface{} // TODO: Make this faster? mfi.merge = func(dst, src pointer) { su := src.asPointerTo(tf).Elem() if !su.IsNil() { du := dst.asPointerTo(tf).Elem() typ := su.Elem().Type() if du.IsNil() || du.Elem().Type() != typ { du.Set(reflect.New(typ.Elem())) // Initialize interface if empty } sv := su.Elem().Elem().Field(0) if sv.Kind() == reflect.Ptr && sv.IsNil() { return } dv := du.Elem().Elem().Field(0) if dv.Kind() == reflect.Ptr && dv.IsNil() { dv.Set(reflect.New(sv.Type().Elem())) // Initialize proto message if empty } switch sv.Type().Kind() { case reflect.Ptr: // Proto struct (e.g., *T) Merge(dv.Interface().(Message), sv.Interface().(Message)) case reflect.Slice: // E.g. Bytes type (e.g., []byte) dv.Set(reflect.ValueOf(append([]byte{}, sv.Bytes()...))) default: // Basic type (e.g., string) dv.Set(sv) } } } } default: panic(fmt.Sprintf("merger not found for type:%s", tf)) } mi.fields = append(mi.fields, mfi) } mi.unrecognized = invalidField if f, ok := t.FieldByName("XXX_unrecognized"); ok { if f.Type != reflect.TypeOf([]byte{}) { panic("expected XXX_unrecognized to be of type []byte") } mi.unrecognized = toField(&f) } atomic.StoreInt32(&mi.initialized, 1) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gogo/protobuf/proto/discard.go
vendor/github.com/gogo/protobuf/proto/discard.go
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2017 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // 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. package proto import ( "fmt" "reflect" "strings" "sync" "sync/atomic" ) type generatedDiscarder interface { XXX_DiscardUnknown() } // DiscardUnknown recursively discards all unknown fields from this message // and all embedded messages. // // When unmarshaling a message with unrecognized fields, the tags and values // of such fields are preserved in the Message. This allows a later call to // marshal to be able to produce a message that continues to have those // unrecognized fields. To avoid this, DiscardUnknown is used to // explicitly clear the unknown fields after unmarshaling. // // For proto2 messages, the unknown fields of message extensions are only // discarded from messages that have been accessed via GetExtension. func DiscardUnknown(m Message) { if m, ok := m.(generatedDiscarder); ok { m.XXX_DiscardUnknown() return } // TODO: Dynamically populate a InternalMessageInfo for legacy messages, // but the master branch has no implementation for InternalMessageInfo, // so it would be more work to replicate that approach. discardLegacy(m) } // DiscardUnknown recursively discards all unknown fields. func (a *InternalMessageInfo) DiscardUnknown(m Message) { di := atomicLoadDiscardInfo(&a.discard) if di == nil { di = getDiscardInfo(reflect.TypeOf(m).Elem()) atomicStoreDiscardInfo(&a.discard, di) } di.discard(toPointer(&m)) } type discardInfo struct { typ reflect.Type initialized int32 // 0: only typ is valid, 1: everything is valid lock sync.Mutex fields []discardFieldInfo unrecognized field } type discardFieldInfo struct { field field // Offset of field, guaranteed to be valid discard func(src pointer) } var ( discardInfoMap = map[reflect.Type]*discardInfo{} discardInfoLock sync.Mutex ) func getDiscardInfo(t reflect.Type) *discardInfo { discardInfoLock.Lock() defer discardInfoLock.Unlock() di := discardInfoMap[t] if di == nil { di = &discardInfo{typ: t} discardInfoMap[t] = di } return di } func (di *discardInfo) discard(src pointer) { if src.isNil() { return // Nothing to do. } if atomic.LoadInt32(&di.initialized) == 0 { di.computeDiscardInfo() } for _, fi := range di.fields { sfp := src.offset(fi.field) fi.discard(sfp) } // For proto2 messages, only discard unknown fields in message extensions // that have been accessed via GetExtension. if em, err := extendable(src.asPointerTo(di.typ).Interface()); err == nil { // Ignore lock since DiscardUnknown is not concurrency safe. emm, _ := em.extensionsRead() for _, mx := range emm { if m, ok := mx.value.(Message); ok { DiscardUnknown(m) } } } if di.unrecognized.IsValid() { *src.offset(di.unrecognized).toBytes() = nil } } func (di *discardInfo) computeDiscardInfo() { di.lock.Lock() defer di.lock.Unlock() if di.initialized != 0 { return } t := di.typ n := t.NumField() for i := 0; i < n; i++ { f := t.Field(i) if strings.HasPrefix(f.Name, "XXX_") { continue } dfi := discardFieldInfo{field: toField(&f)} tf := f.Type // Unwrap tf to get its most basic type. var isPointer, isSlice bool if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { isSlice = true tf = tf.Elem() } if tf.Kind() == reflect.Ptr { isPointer = true tf = tf.Elem() } if isPointer && isSlice && tf.Kind() != reflect.Struct { panic(fmt.Sprintf("%v.%s cannot be a slice of pointers to primitive types", t, f.Name)) } switch tf.Kind() { case reflect.Struct: switch { case !isPointer: panic(fmt.Sprintf("%v.%s cannot be a direct struct value", t, f.Name)) case isSlice: // E.g., []*pb.T discardInfo := getDiscardInfo(tf) dfi.discard = func(src pointer) { sps := src.getPointerSlice() for _, sp := range sps { if !sp.isNil() { discardInfo.discard(sp) } } } default: // E.g., *pb.T discardInfo := getDiscardInfo(tf) dfi.discard = func(src pointer) { sp := src.getPointer() if !sp.isNil() { discardInfo.discard(sp) } } } case reflect.Map: switch { case isPointer || isSlice: panic(fmt.Sprintf("%v.%s cannot be a pointer to a map or a slice of map values", t, f.Name)) default: // E.g., map[K]V if tf.Elem().Kind() == reflect.Ptr { // Proto struct (e.g., *T) dfi.discard = func(src pointer) { sm := src.asPointerTo(tf).Elem() if sm.Len() == 0 { return } for _, key := range sm.MapKeys() { val := sm.MapIndex(key) DiscardUnknown(val.Interface().(Message)) } } } else { dfi.discard = func(pointer) {} // Noop } } case reflect.Interface: // Must be oneof field. switch { case isPointer || isSlice: panic(fmt.Sprintf("%v.%s cannot be a pointer to a interface or a slice of interface values", t, f.Name)) default: // E.g., interface{} // TODO: Make this faster? dfi.discard = func(src pointer) { su := src.asPointerTo(tf).Elem() if !su.IsNil() { sv := su.Elem().Elem().Field(0) if sv.Kind() == reflect.Ptr && sv.IsNil() { return } switch sv.Type().Kind() { case reflect.Ptr: // Proto struct (e.g., *T) DiscardUnknown(sv.Interface().(Message)) } } } } default: continue } di.fields = append(di.fields, dfi) } di.unrecognized = invalidField if f, ok := t.FieldByName("XXX_unrecognized"); ok { if f.Type != reflect.TypeOf([]byte{}) { panic("expected XXX_unrecognized to be of type []byte") } di.unrecognized = toField(&f) } atomic.StoreInt32(&di.initialized, 1) } func discardLegacy(m Message) { v := reflect.ValueOf(m) if v.Kind() != reflect.Ptr || v.IsNil() { return } v = v.Elem() if v.Kind() != reflect.Struct { return } t := v.Type() for i := 0; i < v.NumField(); i++ { f := t.Field(i) if strings.HasPrefix(f.Name, "XXX_") { continue } vf := v.Field(i) tf := f.Type // Unwrap tf to get its most basic type. var isPointer, isSlice bool if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 { isSlice = true tf = tf.Elem() } if tf.Kind() == reflect.Ptr { isPointer = true tf = tf.Elem() } if isPointer && isSlice && tf.Kind() != reflect.Struct { panic(fmt.Sprintf("%T.%s cannot be a slice of pointers to primitive types", m, f.Name)) } switch tf.Kind() { case reflect.Struct: switch { case !isPointer: panic(fmt.Sprintf("%T.%s cannot be a direct struct value", m, f.Name)) case isSlice: // E.g., []*pb.T for j := 0; j < vf.Len(); j++ { discardLegacy(vf.Index(j).Interface().(Message)) } default: // E.g., *pb.T discardLegacy(vf.Interface().(Message)) } case reflect.Map: switch { case isPointer || isSlice: panic(fmt.Sprintf("%T.%s cannot be a pointer to a map or a slice of map values", m, f.Name)) default: // E.g., map[K]V tv := vf.Type().Elem() if tv.Kind() == reflect.Ptr && tv.Implements(protoMessageType) { // Proto struct (e.g., *T) for _, key := range vf.MapKeys() { val := vf.MapIndex(key) discardLegacy(val.Interface().(Message)) } } } case reflect.Interface: // Must be oneof field. switch { case isPointer || isSlice: panic(fmt.Sprintf("%T.%s cannot be a pointer to a interface or a slice of interface values", m, f.Name)) default: // E.g., test_proto.isCommunique_Union interface if !vf.IsNil() && f.Tag.Get("protobuf_oneof") != "" { vf = vf.Elem() // E.g., *test_proto.Communique_Msg if !vf.IsNil() { vf = vf.Elem() // E.g., test_proto.Communique_Msg vf = vf.Field(0) // E.g., Proto struct (e.g., *T) or primitive value if vf.Kind() == reflect.Ptr { discardLegacy(vf.Interface().(Message)) } } } } } } if vf := v.FieldByName("XXX_unrecognized"); vf.IsValid() { if vf.Type() != reflect.TypeOf([]byte{}) { panic("expected XXX_unrecognized to be of type []byte") } vf.Set(reflect.ValueOf([]byte(nil))) } // For proto2 messages, only discard unknown fields in message extensions // that have been accessed via GetExtension. if em, err := extendable(m); err == nil { // Ignore lock since discardLegacy is not concurrency safe. emm, _ := em.extensionsRead() for _, mx := range emm { if m, ok := mx.value.(Message); ok { discardLegacy(m) } } } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gogo/protobuf/proto/clone.go
vendor/github.com/gogo/protobuf/proto/clone.go
// Go support for Protocol Buffers - Google's data interchange format // // Copyright 2011 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // 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. // Protocol buffer deep copy and merge. // TODO: RawMessage. package proto import ( "fmt" "log" "reflect" "strings" ) // Clone returns a deep copy of a protocol buffer. func Clone(src Message) Message { in := reflect.ValueOf(src) if in.IsNil() { return src } out := reflect.New(in.Type().Elem()) dst := out.Interface().(Message) Merge(dst, src) return dst } // Merger is the interface representing objects that can merge messages of the same type. type Merger interface { // Merge merges src into this message. // Required and optional fields that are set in src will be set to that value in dst. // Elements of repeated fields will be appended. // // Merge may panic if called with a different argument type than the receiver. Merge(src Message) } // generatedMerger is the custom merge method that generated protos will have. // We must add this method since a generate Merge method will conflict with // many existing protos that have a Merge data field already defined. type generatedMerger interface { XXX_Merge(src Message) } // Merge merges src into dst. // Required and optional fields that are set in src will be set to that value in dst. // Elements of repeated fields will be appended. // Merge panics if src and dst are not the same type, or if dst is nil. func Merge(dst, src Message) { if m, ok := dst.(Merger); ok { m.Merge(src) return } in := reflect.ValueOf(src) out := reflect.ValueOf(dst) if out.IsNil() { panic("proto: nil destination") } if in.Type() != out.Type() { panic(fmt.Sprintf("proto.Merge(%T, %T) type mismatch", dst, src)) } if in.IsNil() { return // Merge from nil src is a noop } if m, ok := dst.(generatedMerger); ok { m.XXX_Merge(src) return } mergeStruct(out.Elem(), in.Elem()) } func mergeStruct(out, in reflect.Value) { sprop := GetProperties(in.Type()) for i := 0; i < in.NumField(); i++ { f := in.Type().Field(i) if strings.HasPrefix(f.Name, "XXX_") { continue } mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i]) } if emIn, ok := in.Addr().Interface().(extensionsBytes); ok { emOut := out.Addr().Interface().(extensionsBytes) bIn := emIn.GetExtensions() bOut := emOut.GetExtensions() *bOut = append(*bOut, *bIn...) } else if emIn, err := extendable(in.Addr().Interface()); err == nil { emOut, _ := extendable(out.Addr().Interface()) mIn, muIn := emIn.extensionsRead() if mIn != nil { mOut := emOut.extensionsWrite() muIn.Lock() mergeExtension(mOut, mIn) muIn.Unlock() } } uf := in.FieldByName("XXX_unrecognized") if !uf.IsValid() { return } uin := uf.Bytes() if len(uin) > 0 { out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...)) } } // mergeAny performs a merge between two values of the same type. // viaPtr indicates whether the values were indirected through a pointer (implying proto2). // prop is set if this is a struct field (it may be nil). func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) { if in.Type() == protoMessageType { if !in.IsNil() { if out.IsNil() { out.Set(reflect.ValueOf(Clone(in.Interface().(Message)))) } else { Merge(out.Interface().(Message), in.Interface().(Message)) } } return } switch in.Kind() { case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, reflect.String, reflect.Uint32, reflect.Uint64: if !viaPtr && isProto3Zero(in) { return } out.Set(in) case reflect.Interface: // Probably a oneof field; copy non-nil values. if in.IsNil() { return } // Allocate destination if it is not set, or set to a different type. // Otherwise we will merge as normal. if out.IsNil() || out.Elem().Type() != in.Elem().Type() { out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T) } mergeAny(out.Elem(), in.Elem(), false, nil) case reflect.Map: if in.Len() == 0 { return } if out.IsNil() { out.Set(reflect.MakeMap(in.Type())) } // For maps with value types of *T or []byte we need to deep copy each value. elemKind := in.Type().Elem().Kind() for _, key := range in.MapKeys() { var val reflect.Value switch elemKind { case reflect.Ptr: val = reflect.New(in.Type().Elem().Elem()) mergeAny(val, in.MapIndex(key), false, nil) case reflect.Slice: val = in.MapIndex(key) val = reflect.ValueOf(append([]byte{}, val.Bytes()...)) default: val = in.MapIndex(key) } out.SetMapIndex(key, val) } case reflect.Ptr: if in.IsNil() { return } if out.IsNil() { out.Set(reflect.New(in.Elem().Type())) } mergeAny(out.Elem(), in.Elem(), true, nil) case reflect.Slice: if in.IsNil() { return } if in.Type().Elem().Kind() == reflect.Uint8 { // []byte is a scalar bytes field, not a repeated field. // Edge case: if this is in a proto3 message, a zero length // bytes field is considered the zero value, and should not // be merged. if prop != nil && prop.proto3 && in.Len() == 0 { return } // Make a deep copy. // Append to []byte{} instead of []byte(nil) so that we never end up // with a nil result. out.SetBytes(append([]byte{}, in.Bytes()...)) return } n := in.Len() if out.IsNil() { out.Set(reflect.MakeSlice(in.Type(), 0, n)) } switch in.Type().Elem().Kind() { case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, reflect.String, reflect.Uint32, reflect.Uint64: out.Set(reflect.AppendSlice(out, in)) default: for i := 0; i < n; i++ { x := reflect.Indirect(reflect.New(in.Type().Elem())) mergeAny(x, in.Index(i), false, nil) out.Set(reflect.Append(out, x)) } } case reflect.Struct: mergeStruct(out, in) default: // unknown type, so not a protocol buffer log.Printf("proto: don't know how to copy %v", in) } } func mergeExtension(out, in map[int32]Extension) { for extNum, eIn := range in { eOut := Extension{desc: eIn.desc} if eIn.value != nil { v := reflect.New(reflect.TypeOf(eIn.value)).Elem() mergeAny(v, reflect.ValueOf(eIn.value), false, nil) eOut.value = v.Interface() } if eIn.enc != nil { eOut.enc = make([]byte, len(eIn.enc)) copy(eOut.enc, eIn.enc) } out[extNum] = eOut } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/gogo/protobuf/proto/text_parser.go
vendor/github.com/gogo/protobuf/proto/text_parser.go
// Protocol Buffers for Go with Gadgets // // Copyright (c) 2013, The GoGo Authors. All rights reserved. // http://github.com/gogo/protobuf // // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2010 The Go Authors. All rights reserved. // https://github.com/golang/protobuf // // 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. package proto // Functions for parsing the Text protocol buffer format. // TODO: message sets. import ( "encoding" "errors" "fmt" "reflect" "strconv" "strings" "time" "unicode/utf8" ) // Error string emitted when deserializing Any and fields are already set const anyRepeatedlyUnpacked = "Any message unpacked multiple times, or %q already set" type ParseError struct { Message string Line int // 1-based line number Offset int // 0-based byte offset from start of input } func (p *ParseError) Error() string { if p.Line == 1 { // show offset only for first line return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message) } return fmt.Sprintf("line %d: %v", p.Line, p.Message) } type token struct { value string err *ParseError line int // line number offset int // byte number from start of input, not start of line unquoted string // the unquoted version of value, if it was a quoted string } func (t *token) String() string { if t.err == nil { return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset) } return fmt.Sprintf("parse error: %v", t.err) } type textParser struct { s string // remaining input done bool // whether the parsing is finished (success or error) backed bool // whether back() was called offset, line int cur token } func newTextParser(s string) *textParser { p := new(textParser) p.s = s p.line = 1 p.cur.line = 1 return p } func (p *textParser) errorf(format string, a ...interface{}) *ParseError { pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset} p.cur.err = pe p.done = true return pe } // Numbers and identifiers are matched by [-+._A-Za-z0-9] func isIdentOrNumberChar(c byte) bool { switch { case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z': return true case '0' <= c && c <= '9': return true } switch c { case '-', '+', '.', '_': return true } return false } func isWhitespace(c byte) bool { switch c { case ' ', '\t', '\n', '\r': return true } return false } func isQuote(c byte) bool { switch c { case '"', '\'': return true } return false } func (p *textParser) skipWhitespace() { i := 0 for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') { if p.s[i] == '#' { // comment; skip to end of line or input for i < len(p.s) && p.s[i] != '\n' { i++ } if i == len(p.s) { break } } if p.s[i] == '\n' { p.line++ } i++ } p.offset += i p.s = p.s[i:len(p.s)] if len(p.s) == 0 { p.done = true } } func (p *textParser) advance() { // Skip whitespace p.skipWhitespace() if p.done { return } // Start of non-whitespace p.cur.err = nil p.cur.offset, p.cur.line = p.offset, p.line p.cur.unquoted = "" switch p.s[0] { case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/': // Single symbol p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)] case '"', '\'': // Quoted string i := 1 for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' { if p.s[i] == '\\' && i+1 < len(p.s) { // skip escaped char i++ } i++ } if i >= len(p.s) || p.s[i] != p.s[0] { p.errorf("unmatched quote") return } unq, err := unquoteC(p.s[1:i], rune(p.s[0])) if err != nil { p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err) return } p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)] p.cur.unquoted = unq default: i := 0 for i < len(p.s) && isIdentOrNumberChar(p.s[i]) { i++ } if i == 0 { p.errorf("unexpected byte %#x", p.s[0]) return } p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)] } p.offset += len(p.cur.value) } var ( errBadUTF8 = errors.New("proto: bad UTF-8") ) func unquoteC(s string, quote rune) (string, error) { // This is based on C++'s tokenizer.cc. // Despite its name, this is *not* parsing C syntax. // For instance, "\0" is an invalid quoted string. // Avoid allocation in trivial cases. simple := true for _, r := range s { if r == '\\' || r == quote { simple = false break } } if simple { return s, nil } buf := make([]byte, 0, 3*len(s)/2) for len(s) > 0 { r, n := utf8.DecodeRuneInString(s) if r == utf8.RuneError && n == 1 { return "", errBadUTF8 } s = s[n:] if r != '\\' { if r < utf8.RuneSelf { buf = append(buf, byte(r)) } else { buf = append(buf, string(r)...) } continue } ch, tail, err := unescape(s) if err != nil { return "", err } buf = append(buf, ch...) s = tail } return string(buf), nil } func unescape(s string) (ch string, tail string, err error) { r, n := utf8.DecodeRuneInString(s) if r == utf8.RuneError && n == 1 { return "", "", errBadUTF8 } s = s[n:] switch r { case 'a': return "\a", s, nil case 'b': return "\b", s, nil case 'f': return "\f", s, nil case 'n': return "\n", s, nil case 'r': return "\r", s, nil case 't': return "\t", s, nil case 'v': return "\v", s, nil case '?': return "?", s, nil // trigraph workaround case '\'', '"', '\\': return string(r), s, nil case '0', '1', '2', '3', '4', '5', '6', '7': if len(s) < 2 { return "", "", fmt.Errorf(`\%c requires 2 following digits`, r) } ss := string(r) + s[:2] s = s[2:] i, err := strconv.ParseUint(ss, 8, 8) if err != nil { return "", "", fmt.Errorf(`\%s contains non-octal digits`, ss) } return string([]byte{byte(i)}), s, nil case 'x', 'X', 'u', 'U': var n int switch r { case 'x', 'X': n = 2 case 'u': n = 4 case 'U': n = 8 } if len(s) < n { return "", "", fmt.Errorf(`\%c requires %d following digits`, r, n) } ss := s[:n] s = s[n:] i, err := strconv.ParseUint(ss, 16, 64) if err != nil { return "", "", fmt.Errorf(`\%c%s contains non-hexadecimal digits`, r, ss) } if r == 'x' || r == 'X' { return string([]byte{byte(i)}), s, nil } if i > utf8.MaxRune { return "", "", fmt.Errorf(`\%c%s is not a valid Unicode code point`, r, ss) } return string(rune(i)), s, nil } return "", "", fmt.Errorf(`unknown escape \%c`, r) } // Back off the parser by one token. Can only be done between calls to next(). // It makes the next advance() a no-op. func (p *textParser) back() { p.backed = true } // Advances the parser and returns the new current token. func (p *textParser) next() *token { if p.backed || p.done { p.backed = false return &p.cur } p.advance() if p.done { p.cur.value = "" } else if len(p.cur.value) > 0 && isQuote(p.cur.value[0]) { // Look for multiple quoted strings separated by whitespace, // and concatenate them. cat := p.cur for { p.skipWhitespace() if p.done || !isQuote(p.s[0]) { break } p.advance() if p.cur.err != nil { return &p.cur } cat.value += " " + p.cur.value cat.unquoted += p.cur.unquoted } p.done = false // parser may have seen EOF, but we want to return cat p.cur = cat } return &p.cur } func (p *textParser) consumeToken(s string) error { tok := p.next() if tok.err != nil { return tok.err } if tok.value != s { p.back() return p.errorf("expected %q, found %q", s, tok.value) } return nil } // Return a RequiredNotSetError indicating which required field was not set. func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError { st := sv.Type() sprops := GetProperties(st) for i := 0; i < st.NumField(); i++ { if !isNil(sv.Field(i)) { continue } props := sprops.Prop[i] if props.Required { return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)} } } return &RequiredNotSetError{fmt.Sprintf("%v.<unknown field name>", st)} // should not happen } // Returns the index in the struct for the named field, as well as the parsed tag properties. func structFieldByName(sprops *StructProperties, name string) (int, *Properties, bool) { i, ok := sprops.decoderOrigNames[name] if ok { return i, sprops.Prop[i], true } return -1, nil, false } // Consume a ':' from the input stream (if the next token is a colon), // returning an error if a colon is needed but not present. func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError { tok := p.next() if tok.err != nil { return tok.err } if tok.value != ":" { // Colon is optional when the field is a group or message. needColon := true switch props.Wire { case "group": needColon = false case "bytes": // A "bytes" field is either a message, a string, or a repeated field; // those three become *T, *string and []T respectively, so we can check for // this field being a pointer to a non-string. if typ.Kind() == reflect.Ptr { // *T or *string if typ.Elem().Kind() == reflect.String { break } } else if typ.Kind() == reflect.Slice { // []T or []*T if typ.Elem().Kind() != reflect.Ptr { break } } else if typ.Kind() == reflect.String { // The proto3 exception is for a string field, // which requires a colon. break } needColon = false } if needColon { return p.errorf("expected ':', found %q", tok.value) } p.back() } return nil } func (p *textParser) readStruct(sv reflect.Value, terminator string) error { st := sv.Type() sprops := GetProperties(st) reqCount := sprops.reqCount var reqFieldErr error fieldSet := make(map[string]bool) // A struct is a sequence of "name: value", terminated by one of // '>' or '}', or the end of the input. A name may also be // "[extension]" or "[type/url]". // // The whole struct can also be an expanded Any message, like: // [type/url] < ... struct contents ... > for { tok := p.next() if tok.err != nil { return tok.err } if tok.value == terminator { break } if tok.value == "[" { // Looks like an extension or an Any. // // TODO: Check whether we need to handle // namespace rooted names (e.g. ".something.Foo"). extName, err := p.consumeExtName() if err != nil { return err } if s := strings.LastIndex(extName, "/"); s >= 0 { // If it contains a slash, it's an Any type URL. messageName := extName[s+1:] mt := MessageType(messageName) if mt == nil { return p.errorf("unrecognized message %q in google.protobuf.Any", messageName) } tok = p.next() if tok.err != nil { return tok.err } // consume an optional colon if tok.value == ":" { tok = p.next() if tok.err != nil { return tok.err } } var terminator string switch tok.value { case "<": terminator = ">" case "{": terminator = "}" default: return p.errorf("expected '{' or '<', found %q", tok.value) } v := reflect.New(mt.Elem()) if pe := p.readStruct(v.Elem(), terminator); pe != nil { return pe } b, err := Marshal(v.Interface().(Message)) if err != nil { return p.errorf("failed to marshal message of type %q: %v", messageName, err) } if fieldSet["type_url"] { return p.errorf(anyRepeatedlyUnpacked, "type_url") } if fieldSet["value"] { return p.errorf(anyRepeatedlyUnpacked, "value") } sv.FieldByName("TypeUrl").SetString(extName) sv.FieldByName("Value").SetBytes(b) fieldSet["type_url"] = true fieldSet["value"] = true continue } var desc *ExtensionDesc // This could be faster, but it's functional. // TODO: Do something smarter than a linear scan. for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) { if d.Name == extName { desc = d break } } if desc == nil { return p.errorf("unrecognized extension %q", extName) } props := &Properties{} props.Parse(desc.Tag) typ := reflect.TypeOf(desc.ExtensionType) if err := p.checkForColon(props, typ); err != nil { return err } rep := desc.repeated() // Read the extension structure, and set it in // the value we're constructing. var ext reflect.Value if !rep { ext = reflect.New(typ).Elem() } else { ext = reflect.New(typ.Elem()).Elem() } if err := p.readAny(ext, props); err != nil { if _, ok := err.(*RequiredNotSetError); !ok { return err } reqFieldErr = err } ep := sv.Addr().Interface().(Message) if !rep { SetExtension(ep, desc, ext.Interface()) } else { old, err := GetExtension(ep, desc) var sl reflect.Value if err == nil { sl = reflect.ValueOf(old) // existing slice } else { sl = reflect.MakeSlice(typ, 0, 1) } sl = reflect.Append(sl, ext) SetExtension(ep, desc, sl.Interface()) } if err := p.consumeOptionalSeparator(); err != nil { return err } continue } // This is a normal, non-extension field. name := tok.value var dst reflect.Value fi, props, ok := structFieldByName(sprops, name) if ok { dst = sv.Field(fi) } else if oop, ok := sprops.OneofTypes[name]; ok { // It is a oneof. props = oop.Prop nv := reflect.New(oop.Type.Elem()) dst = nv.Elem().Field(0) field := sv.Field(oop.Field) if !field.IsNil() { return p.errorf("field '%s' would overwrite already parsed oneof '%s'", name, sv.Type().Field(oop.Field).Name) } field.Set(nv) } if !dst.IsValid() { return p.errorf("unknown field name %q in %v", name, st) } if dst.Kind() == reflect.Map { // Consume any colon. if err := p.checkForColon(props, dst.Type()); err != nil { return err } // Construct the map if it doesn't already exist. if dst.IsNil() { dst.Set(reflect.MakeMap(dst.Type())) } key := reflect.New(dst.Type().Key()).Elem() val := reflect.New(dst.Type().Elem()).Elem() // The map entry should be this sequence of tokens: // < key : KEY value : VALUE > // However, implementations may omit key or value, and technically // we should support them in any order. See b/28924776 for a time // this went wrong. tok := p.next() var terminator string switch tok.value { case "<": terminator = ">" case "{": terminator = "}" default: return p.errorf("expected '{' or '<', found %q", tok.value) } for { tok := p.next() if tok.err != nil { return tok.err } if tok.value == terminator { break } switch tok.value { case "key": if err := p.consumeToken(":"); err != nil { return err } if err := p.readAny(key, props.MapKeyProp); err != nil { return err } if err := p.consumeOptionalSeparator(); err != nil { return err } case "value": if err := p.checkForColon(props.MapValProp, dst.Type().Elem()); err != nil { return err } if err := p.readAny(val, props.MapValProp); err != nil { return err } if err := p.consumeOptionalSeparator(); err != nil { return err } default: p.back() return p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value) } } dst.SetMapIndex(key, val) continue } // Check that it's not already set if it's not a repeated field. if !props.Repeated && fieldSet[name] { return p.errorf("non-repeated field %q was repeated", name) } if err := p.checkForColon(props, dst.Type()); err != nil { return err } // Parse into the field. fieldSet[name] = true if err := p.readAny(dst, props); err != nil { if _, ok := err.(*RequiredNotSetError); !ok { return err } reqFieldErr = err } if props.Required { reqCount-- } if err := p.consumeOptionalSeparator(); err != nil { return err } } if reqCount > 0 { return p.missingRequiredFieldError(sv) } return reqFieldErr } // consumeExtName consumes extension name or expanded Any type URL and the // following ']'. It returns the name or URL consumed. func (p *textParser) consumeExtName() (string, error) { tok := p.next() if tok.err != nil { return "", tok.err } // If extension name or type url is quoted, it's a single token. if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] { name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0])) if err != nil { return "", err } return name, p.consumeToken("]") } // Consume everything up to "]" var parts []string for tok.value != "]" { parts = append(parts, tok.value) tok = p.next() if tok.err != nil { return "", p.errorf("unrecognized type_url or extension name: %s", tok.err) } if p.done && tok.value != "]" { return "", p.errorf("unclosed type_url or extension name") } } return strings.Join(parts, ""), nil } // consumeOptionalSeparator consumes an optional semicolon or comma. // It is used in readStruct to provide backward compatibility. func (p *textParser) consumeOptionalSeparator() error { tok := p.next() if tok.err != nil { return tok.err } if tok.value != ";" && tok.value != "," { p.back() } return nil } func (p *textParser) readAny(v reflect.Value, props *Properties) error { tok := p.next() if tok.err != nil { return tok.err } if tok.value == "" { return p.errorf("unexpected EOF") } if len(props.CustomType) > 0 { if props.Repeated { t := reflect.TypeOf(v.Interface()) if t.Kind() == reflect.Slice { tc := reflect.TypeOf(new(Marshaler)) ok := t.Elem().Implements(tc.Elem()) if ok { fv := v flen := fv.Len() if flen == fv.Cap() { nav := reflect.MakeSlice(v.Type(), flen, 2*flen+1) reflect.Copy(nav, fv) fv.Set(nav) } fv.SetLen(flen + 1) // Read one. p.back() return p.readAny(fv.Index(flen), props) } } } if reflect.TypeOf(v.Interface()).Kind() == reflect.Ptr { custom := reflect.New(props.ctype.Elem()).Interface().(Unmarshaler) err := custom.Unmarshal([]byte(tok.unquoted)) if err != nil { return p.errorf("%v %v: %v", err, v.Type(), tok.value) } v.Set(reflect.ValueOf(custom)) } else { custom := reflect.New(reflect.TypeOf(v.Interface())).Interface().(Unmarshaler) err := custom.Unmarshal([]byte(tok.unquoted)) if err != nil { return p.errorf("%v %v: %v", err, v.Type(), tok.value) } v.Set(reflect.Indirect(reflect.ValueOf(custom))) } return nil } if props.StdTime { fv := v p.back() props.StdTime = false tproto := &timestamp{} err := p.readAny(reflect.ValueOf(tproto).Elem(), props) props.StdTime = true if err != nil { return err } tim, err := timestampFromProto(tproto) if err != nil { return err } if props.Repeated { t := reflect.TypeOf(v.Interface()) if t.Kind() == reflect.Slice { if t.Elem().Kind() == reflect.Ptr { ts := fv.Interface().([]*time.Time) ts = append(ts, &tim) fv.Set(reflect.ValueOf(ts)) return nil } else { ts := fv.Interface().([]time.Time) ts = append(ts, tim) fv.Set(reflect.ValueOf(ts)) return nil } } } if reflect.TypeOf(v.Interface()).Kind() == reflect.Ptr { v.Set(reflect.ValueOf(&tim)) } else { v.Set(reflect.Indirect(reflect.ValueOf(&tim))) } return nil } if props.StdDuration { fv := v p.back() props.StdDuration = false dproto := &duration{} err := p.readAny(reflect.ValueOf(dproto).Elem(), props) props.StdDuration = true if err != nil { return err } dur, err := durationFromProto(dproto) if err != nil { return err } if props.Repeated { t := reflect.TypeOf(v.Interface()) if t.Kind() == reflect.Slice { if t.Elem().Kind() == reflect.Ptr { ds := fv.Interface().([]*time.Duration) ds = append(ds, &dur) fv.Set(reflect.ValueOf(ds)) return nil } else { ds := fv.Interface().([]time.Duration) ds = append(ds, dur) fv.Set(reflect.ValueOf(ds)) return nil } } } if reflect.TypeOf(v.Interface()).Kind() == reflect.Ptr { v.Set(reflect.ValueOf(&dur)) } else { v.Set(reflect.Indirect(reflect.ValueOf(&dur))) } return nil } switch fv := v; fv.Kind() { case reflect.Slice: at := v.Type() if at.Elem().Kind() == reflect.Uint8 { // Special case for []byte if tok.value[0] != '"' && tok.value[0] != '\'' { // Deliberately written out here, as the error after // this switch statement would write "invalid []byte: ...", // which is not as user-friendly. return p.errorf("invalid string: %v", tok.value) } bytes := []byte(tok.unquoted) fv.Set(reflect.ValueOf(bytes)) return nil } // Repeated field. if tok.value == "[" { // Repeated field with list notation, like [1,2,3]. for { fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) err := p.readAny(fv.Index(fv.Len()-1), props) if err != nil { return err } ntok := p.next() if ntok.err != nil { return ntok.err } if ntok.value == "]" { break } if ntok.value != "," { return p.errorf("Expected ']' or ',' found %q", ntok.value) } } return nil } // One value of the repeated field. p.back() fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) return p.readAny(fv.Index(fv.Len()-1), props) case reflect.Bool: // true/1/t/True or false/f/0/False. switch tok.value { case "true", "1", "t", "True": fv.SetBool(true) return nil case "false", "0", "f", "False": fv.SetBool(false) return nil } case reflect.Float32, reflect.Float64: v := tok.value // Ignore 'f' for compatibility with output generated by C++, but don't // remove 'f' when the value is "-inf" or "inf". if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" { v = v[:len(v)-1] } if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil { fv.SetFloat(f) return nil } case reflect.Int8: if x, err := strconv.ParseInt(tok.value, 0, 8); err == nil { fv.SetInt(x) return nil } case reflect.Int16: if x, err := strconv.ParseInt(tok.value, 0, 16); err == nil { fv.SetInt(x) return nil } case reflect.Int32: if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil { fv.SetInt(x) return nil } if len(props.Enum) == 0 { break } m, ok := enumValueMaps[props.Enum] if !ok { break } x, ok := m[tok.value] if !ok { break } fv.SetInt(int64(x)) return nil case reflect.Int64: if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil { fv.SetInt(x) return nil } case reflect.Ptr: // A basic field (indirected through pointer), or a repeated message/group p.back() fv.Set(reflect.New(fv.Type().Elem())) return p.readAny(fv.Elem(), props) case reflect.String: if tok.value[0] == '"' || tok.value[0] == '\'' { fv.SetString(tok.unquoted) return nil } case reflect.Struct: var terminator string switch tok.value { case "{": terminator = "}" case "<": terminator = ">" default: return p.errorf("expected '{' or '<', found %q", tok.value) } // TODO: Handle nested messages which implement encoding.TextUnmarshaler. return p.readStruct(fv, terminator) case reflect.Uint8: if x, err := strconv.ParseUint(tok.value, 0, 8); err == nil { fv.SetUint(x) return nil } case reflect.Uint16: if x, err := strconv.ParseUint(tok.value, 0, 16); err == nil { fv.SetUint(x) return nil } case reflect.Uint32: if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil { fv.SetUint(uint64(x)) return nil } case reflect.Uint64: if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil { fv.SetUint(x) return nil } } return p.errorf("invalid %v: %v", v.Type(), tok.value) } // UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb // before starting to unmarshal, so any existing data in pb is always removed. // If a required field is not set and no other error occurs, // UnmarshalText returns *RequiredNotSetError. func UnmarshalText(s string, pb Message) error { if um, ok := pb.(encoding.TextUnmarshaler); ok { return um.UnmarshalText([]byte(s)) } pb.Reset() v := reflect.ValueOf(pb) return newTextParser(s).readStruct(v.Elem(), "") }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false