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/vmware/govmomi/view/container_view.go | vendor/github.com/vmware/govmomi/view/container_view.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package view
import (
"context"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
type ContainerView struct {
ManagedObjectView
}
func NewContainerView(c *vim25.Client, ref types.ManagedObjectReference) *ContainerView {
return &ContainerView{
ManagedObjectView: *NewManagedObjectView(c, ref),
}
}
// Retrieve populates dst as property.Collector.Retrieve does, for all entities in the view of types specified by kind.
func (v ContainerView) Retrieve(ctx context.Context, kind []string, ps []string, dst any, pspec ...types.PropertySpec) error {
pc := property.DefaultCollector(v.Client())
ospec := types.ObjectSpec{
Obj: v.Reference(),
Skip: types.NewBool(true),
SelectSet: []types.BaseSelectionSpec{
&types.TraversalSpec{
Type: v.Reference().Type,
Path: "view",
},
},
}
if len(kind) == 0 {
kind = []string{"ManagedEntity"}
}
for _, t := range kind {
spec := types.PropertySpec{
Type: t,
}
if len(ps) == 0 {
spec.All = types.NewBool(true)
} else {
spec.PathSet = ps
}
pspec = append(pspec, spec)
}
req := types.RetrieveProperties{
SpecSet: []types.PropertyFilterSpec{
{
ObjectSet: []types.ObjectSpec{ospec},
PropSet: pspec,
},
},
}
res, err := pc.RetrieveProperties(ctx, req)
if err != nil {
return err
}
if d, ok := dst.(*[]types.ObjectContent); ok {
*d = res.Returnval
return nil
}
return mo.LoadObjectContent(res.Returnval, dst)
}
// RetrieveWithFilter populates dst as Retrieve does, but only for entities matching the given filter.
func (v ContainerView) RetrieveWithFilter(ctx context.Context, kind []string, ps []string, dst any, filter property.Match) error {
if len(filter) == 0 {
return v.Retrieve(ctx, kind, ps, dst)
}
var content []types.ObjectContent
err := v.Retrieve(ctx, kind, filter.Keys(), &content)
if err != nil {
return err
}
objs := filter.ObjectContent(content)
pc := property.DefaultCollector(v.Client())
return pc.Retrieve(ctx, objs, ps, dst)
}
// Find returns object references for entities of type kind, matching the given filter.
func (v ContainerView) Find(ctx context.Context, kind []string, filter property.Match) ([]types.ManagedObjectReference, error) {
if len(filter) == 0 {
// Ensure we have at least 1 filter to avoid retrieving all properties.
filter = property.Match{"name": "*"}
}
var content []types.ObjectContent
err := v.Retrieve(ctx, kind, filter.Keys(), &content)
if err != nil {
return nil, err
}
return filter.ObjectContent(content), nil
}
// FindAny returns object references for entities of type kind, matching any property the given filter.
func (v ContainerView) FindAny(ctx context.Context, kind []string, filter property.Match) ([]types.ManagedObjectReference, error) {
if len(filter) == 0 {
// Ensure we have at least 1 filter to avoid retrieving all properties.
filter = property.Match{"name": "*"}
}
var content []types.ObjectContent
err := v.Retrieve(ctx, kind, filter.Keys(), &content)
if err != nil {
return nil, err
}
return filter.AnyObjectContent(content), 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/vmware/govmomi/view/manager.go | vendor/github.com/vmware/govmomi/view/manager.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package view
import (
"context"
"github.com/vmware/govmomi/object"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type Manager struct {
object.Common
}
func NewManager(c *vim25.Client) *Manager {
m := Manager{
object.NewCommon(c, *c.ServiceContent.ViewManager),
}
return &m
}
func (m Manager) CreateListView(ctx context.Context, objects []types.ManagedObjectReference) (*ListView, error) {
req := types.CreateListView{
This: m.Common.Reference(),
Obj: objects,
}
res, err := methods.CreateListView(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return NewListView(m.Client(), res.Returnval), nil
}
func (m Manager) CreateContainerView(ctx context.Context, container types.ManagedObjectReference, managedObjectTypes []string, recursive bool) (*ContainerView, error) {
req := types.CreateContainerView{
This: m.Common.Reference(),
Container: container,
Recursive: recursive,
Type: managedObjectTypes,
}
res, err := methods.CreateContainerView(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return NewContainerView(m.Client(), res.Returnval), 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/vmware/govmomi/internal/types.go | vendor/github.com/vmware/govmomi/internal/types.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package internal
import (
"reflect"
"github.com/vmware/govmomi/vim25/types"
)
type VimEsxCLICLIFault struct {
types.MethodFault
ErrMsg []string `xml:"errMsg"`
}
func init() {
types.Add("VimEsxCLICLIFault", reflect.TypeOf((*VimEsxCLICLIFault)(nil)).Elem())
}
type DynamicTypeMgrQueryMoInstancesRequest struct {
This types.ManagedObjectReference `xml:"_this"`
FilterSpec BaseDynamicTypeMgrFilterSpec `xml:"filterSpec,omitempty,typeattr"`
}
func init() {
types.Add("DynamicTypeMgrQueryMoInstances", reflect.TypeOf((*DynamicTypeMgrQueryMoInstancesRequest)(nil)).Elem())
}
type DynamicTypeMgrQueryMoInstancesResponse struct {
Returnval []DynamicTypeMgrMoInstance `xml:"urn:vim25 returnval"`
}
type DynamicTypeEnumTypeInfo struct {
types.DynamicData
Name string `xml:"name"`
WsdlName string `xml:"wsdlName"`
Version string `xml:"version"`
Value []string `xml:"value,omitempty"`
Annotation []DynamicTypeMgrAnnotation `xml:"annotation,omitempty"`
}
func init() {
types.Add("DynamicTypeEnumTypeInfo", reflect.TypeOf((*DynamicTypeEnumTypeInfo)(nil)).Elem())
}
type DynamicTypeMgrAllTypeInfo struct {
types.DynamicData
ManagedTypeInfo []DynamicTypeMgrManagedTypeInfo `xml:"managedTypeInfo,omitempty"`
EnumTypeInfo []DynamicTypeEnumTypeInfo `xml:"enumTypeInfo,omitempty"`
DataTypeInfo []DynamicTypeMgrDataTypeInfo `xml:"dataTypeInfo,omitempty"`
}
func init() {
types.Add("DynamicTypeMgrAllTypeInfo", reflect.TypeOf((*DynamicTypeMgrAllTypeInfo)(nil)).Elem())
}
type DynamicTypeMgrAnnotation struct {
types.DynamicData
Name string `xml:"name"`
Parameter []string `xml:"parameter,omitempty"`
}
func init() {
types.Add("DynamicTypeMgrAnnotation", reflect.TypeOf((*DynamicTypeMgrAnnotation)(nil)).Elem())
}
type DynamicTypeMgrDataTypeInfo struct {
types.DynamicData
Name string `xml:"name"`
WsdlName string `xml:"wsdlName"`
Version string `xml:"version"`
Base []string `xml:"base,omitempty"`
Property []DynamicTypeMgrPropertyTypeInfo `xml:"property,omitempty"`
Annotation []DynamicTypeMgrAnnotation `xml:"annotation,omitempty"`
}
func init() {
types.Add("DynamicTypeMgrDataTypeInfo", reflect.TypeOf((*DynamicTypeMgrDataTypeInfo)(nil)).Elem())
}
func (b *DynamicTypeMgrFilterSpec) GetDynamicTypeMgrFilterSpec() *DynamicTypeMgrFilterSpec { return b }
type BaseDynamicTypeMgrFilterSpec interface {
GetDynamicTypeMgrFilterSpec() *DynamicTypeMgrFilterSpec
}
type DynamicTypeMgrFilterSpec struct {
types.DynamicData
}
func init() {
types.Add("DynamicTypeMgrFilterSpec", reflect.TypeOf((*DynamicTypeMgrFilterSpec)(nil)).Elem())
}
type DynamicTypeMgrManagedTypeInfo struct {
types.DynamicData
Name string `xml:"name"`
WsdlName string `xml:"wsdlName"`
Version string `xml:"version"`
Base []string `xml:"base,omitempty"`
Property []DynamicTypeMgrPropertyTypeInfo `xml:"property,omitempty"`
Method []DynamicTypeMgrMethodTypeInfo `xml:"method,omitempty"`
Annotation []DynamicTypeMgrAnnotation `xml:"annotation,omitempty"`
}
func init() {
types.Add("DynamicTypeMgrManagedTypeInfo", reflect.TypeOf((*DynamicTypeMgrManagedTypeInfo)(nil)).Elem())
}
type DynamicTypeMgrMethodTypeInfo struct {
types.DynamicData
Name string `xml:"name"`
WsdlName string `xml:"wsdlName"`
Version string `xml:"version"`
ParamTypeInfo []DynamicTypeMgrParamTypeInfo `xml:"paramTypeInfo,omitempty"`
ReturnTypeInfo *DynamicTypeMgrParamTypeInfo `xml:"returnTypeInfo,omitempty"`
Fault []string `xml:"fault,omitempty"`
PrivId string `xml:"privId,omitempty"`
Annotation []DynamicTypeMgrAnnotation `xml:"annotation,omitempty"`
}
func init() {
types.Add("DynamicTypeMgrMethodTypeInfo", reflect.TypeOf((*DynamicTypeMgrMethodTypeInfo)(nil)).Elem())
}
type DynamicTypeMgrMoFilterSpec struct {
DynamicTypeMgrFilterSpec
Id string `xml:"id,omitempty"`
TypeSubstr string `xml:"typeSubstr,omitempty"`
}
func init() {
types.Add("DynamicTypeMgrMoFilterSpec", reflect.TypeOf((*DynamicTypeMgrMoFilterSpec)(nil)).Elem())
}
type DynamicTypeMgrMoInstance struct {
types.DynamicData
Id string `xml:"id"`
MoType string `xml:"moType"`
}
func init() {
types.Add("DynamicTypeMgrMoInstance", reflect.TypeOf((*DynamicTypeMgrMoInstance)(nil)).Elem())
}
type DynamicTypeMgrParamTypeInfo struct {
types.DynamicData
Name string `xml:"name"`
Version string `xml:"version"`
Type string `xml:"type"`
PrivId string `xml:"privId,omitempty"`
Annotation []DynamicTypeMgrAnnotation `xml:"annotation,omitempty"`
}
func init() {
types.Add("DynamicTypeMgrParamTypeInfo", reflect.TypeOf((*DynamicTypeMgrParamTypeInfo)(nil)).Elem())
}
type DynamicTypeMgrPropertyTypeInfo struct {
types.DynamicData
Name string `xml:"name"`
Version string `xml:"version"`
Type string `xml:"type"`
PrivId string `xml:"privId,omitempty"`
MsgIdFormat string `xml:"msgIdFormat,omitempty"`
Annotation []DynamicTypeMgrAnnotation `xml:"annotation,omitempty"`
}
type DynamicTypeMgrQueryTypeInfoRequest struct {
This types.ManagedObjectReference `xml:"_this"`
FilterSpec BaseDynamicTypeMgrFilterSpec `xml:"filterSpec,omitempty,typeattr"`
}
func init() {
types.Add("DynamicTypeMgrQueryTypeInfo", reflect.TypeOf((*DynamicTypeMgrQueryTypeInfoRequest)(nil)).Elem())
}
type DynamicTypeMgrQueryTypeInfoResponse struct {
Returnval DynamicTypeMgrAllTypeInfo `xml:"urn:vim25 returnval"`
}
func init() {
types.Add("DynamicTypeMgrPropertyTypeInfo", reflect.TypeOf((*DynamicTypeMgrPropertyTypeInfo)(nil)).Elem())
}
type DynamicTypeMgrTypeFilterSpec struct {
DynamicTypeMgrFilterSpec
TypeSubstr string `xml:"typeSubstr,omitempty"`
}
func init() {
types.Add("DynamicTypeMgrTypeFilterSpec", reflect.TypeOf((*DynamicTypeMgrTypeFilterSpec)(nil)).Elem())
}
type ReflectManagedMethodExecuterSoapArgument struct {
types.DynamicData
Name string `xml:"name"`
Val string `xml:"val"`
}
func init() {
types.Add("ReflectManagedMethodExecuterSoapArgument", reflect.TypeOf((*ReflectManagedMethodExecuterSoapArgument)(nil)).Elem())
}
type ReflectManagedMethodExecuterSoapFault struct {
types.DynamicData
FaultMsg string `xml:"faultMsg"`
FaultDetail string `xml:"faultDetail,omitempty"`
}
func init() {
types.Add("ReflectManagedMethodExecuterSoapFault", reflect.TypeOf((*ReflectManagedMethodExecuterSoapFault)(nil)).Elem())
}
type ReflectManagedMethodExecuterSoapResult struct {
types.DynamicData
Response string `xml:"response,omitempty"`
Fault *ReflectManagedMethodExecuterSoapFault `xml:"fault,omitempty"`
}
type RetrieveDynamicTypeManagerRequest struct {
This types.ManagedObjectReference `xml:"_this"`
}
type RetrieveDynamicTypeManagerResponse struct {
Returnval *InternalDynamicTypeManager `xml:"urn:vim25 returnval"`
}
func init() {
types.Add("RetrieveDynamicTypeManager", reflect.TypeOf((*RetrieveDynamicTypeManagerRequest)(nil)).Elem())
}
type RetrieveManagedMethodExecuterRequest struct {
This types.ManagedObjectReference `xml:"_this"`
}
func init() {
types.Add("RetrieveManagedMethodExecuter", reflect.TypeOf((*RetrieveManagedMethodExecuterRequest)(nil)).Elem())
}
type RetrieveManagedMethodExecuterResponse struct {
Returnval *ReflectManagedMethodExecuter `xml:"urn:vim25 returnval"`
}
type InternalDynamicTypeManager struct {
types.ManagedObjectReference
}
type ReflectManagedMethodExecuter struct {
types.ManagedObjectReference
}
type ExecuteSoapRequest struct {
This types.ManagedObjectReference `xml:"_this"`
Moid string `xml:"moid"`
Version string `xml:"version"`
Method string `xml:"method"`
Argument []ReflectManagedMethodExecuterSoapArgument `xml:"argument,omitempty"`
}
type ExecuteSoapResponse struct {
Returnval *ReflectManagedMethodExecuterSoapResult `xml:"urn:vim25 returnval"`
}
func init() {
types.Add("ExecuteSoap", reflect.TypeOf((*ExecuteSoapRequest)(nil)).Elem())
types.Add("ArrayOfVirtualDiskInfo", reflect.TypeOf((*ArrayOfVirtualDiskInfo)(nil)).Elem())
types.Add("VirtualDiskInfo", reflect.TypeOf((*VirtualDiskInfo)(nil)).Elem())
types.Add("QueryVirtualDiskInfo_Task", reflect.TypeOf((*QueryVirtualDiskInfoTaskRequest)(nil)).Elem())
}
type VirtualDiskInfo struct {
Name string `xml:"unit>name"`
DiskType string `xml:"diskType"`
Parent string `xml:"parent,omitempty"`
}
type ArrayOfVirtualDiskInfo struct {
VirtualDiskInfo []VirtualDiskInfo `xml:"VirtualDiskInfo,omitempty"`
}
type QueryVirtualDiskInfoTaskRequest struct {
This types.ManagedObjectReference `xml:"_this"`
Name string `xml:"name"`
Datacenter *types.ManagedObjectReference `xml:"datacenter,omitempty"`
IncludeParents bool `xml:"includeParents"`
}
type QueryVirtualDiskInfo_TaskResponse struct {
Returnval types.ManagedObjectReference `xml:"returnval"`
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/internal/methods.go | vendor/github.com/vmware/govmomi/internal/methods.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package internal
import (
"context"
"github.com/vmware/govmomi/vim25/soap"
)
type RetrieveDynamicTypeManagerBody struct {
Req *RetrieveDynamicTypeManagerRequest `xml:"urn:vim25 RetrieveDynamicTypeManager"`
Res *RetrieveDynamicTypeManagerResponse `xml:"urn:vim25 RetrieveDynamicTypeManagerResponse"`
Fault_ *soap.Fault
}
func (b *RetrieveDynamicTypeManagerBody) Fault() *soap.Fault { return b.Fault_ }
func RetrieveDynamicTypeManager(ctx context.Context, r soap.RoundTripper, req *RetrieveDynamicTypeManagerRequest) (*RetrieveDynamicTypeManagerResponse, error) {
var reqBody, resBody RetrieveDynamicTypeManagerBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type RetrieveManagedMethodExecuterBody struct {
Req *RetrieveManagedMethodExecuterRequest `xml:"urn:vim25 RetrieveManagedMethodExecuter"`
Res *RetrieveManagedMethodExecuterResponse `xml:"urn:vim25 RetrieveManagedMethodExecuterResponse"`
Fault_ *soap.Fault
}
func (b *RetrieveManagedMethodExecuterBody) Fault() *soap.Fault { return b.Fault_ }
func RetrieveManagedMethodExecuter(ctx context.Context, r soap.RoundTripper, req *RetrieveManagedMethodExecuterRequest) (*RetrieveManagedMethodExecuterResponse, error) {
var reqBody, resBody RetrieveManagedMethodExecuterBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type DynamicTypeMgrQueryMoInstancesBody struct {
Req *DynamicTypeMgrQueryMoInstancesRequest `xml:"urn:vim25 DynamicTypeMgrQueryMoInstances"`
Res *DynamicTypeMgrQueryMoInstancesResponse `xml:"urn:vim25 DynamicTypeMgrQueryMoInstancesResponse"`
Fault_ *soap.Fault
}
func (b *DynamicTypeMgrQueryMoInstancesBody) Fault() *soap.Fault { return b.Fault_ }
func DynamicTypeMgrQueryMoInstances(ctx context.Context, r soap.RoundTripper, req *DynamicTypeMgrQueryMoInstancesRequest) (*DynamicTypeMgrQueryMoInstancesResponse, error) {
var reqBody, resBody DynamicTypeMgrQueryMoInstancesBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type DynamicTypeMgrQueryTypeInfoBody struct {
Req *DynamicTypeMgrQueryTypeInfoRequest `xml:"urn:vim25 DynamicTypeMgrQueryTypeInfo"`
Res *DynamicTypeMgrQueryTypeInfoResponse `xml:"urn:vim25 DynamicTypeMgrQueryTypeInfoResponse"`
Fault_ *soap.Fault
}
func (b *DynamicTypeMgrQueryTypeInfoBody) Fault() *soap.Fault { return b.Fault_ }
func DynamicTypeMgrQueryTypeInfo(ctx context.Context, r soap.RoundTripper, req *DynamicTypeMgrQueryTypeInfoRequest) (*DynamicTypeMgrQueryTypeInfoResponse, error) {
var reqBody, resBody DynamicTypeMgrQueryTypeInfoBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type ExecuteSoapBody struct {
Req *ExecuteSoapRequest `xml:"urn:vim25 ExecuteSoap"`
Res *ExecuteSoapResponse `xml:"urn:vim25 ExecuteSoapResponse"`
Fault_ *soap.Fault
}
func (b *ExecuteSoapBody) Fault() *soap.Fault { return b.Fault_ }
func ExecuteSoap(ctx context.Context, r soap.RoundTripper, req *ExecuteSoapRequest) (*ExecuteSoapResponse, error) {
var reqBody, resBody ExecuteSoapBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
return resBody.Res, nil
}
type QueryVirtualDiskInfoTaskBody struct {
Req *QueryVirtualDiskInfoTaskRequest `xml:"urn:internalvim25 QueryVirtualDiskInfo_Task,omitempty"`
Res *QueryVirtualDiskInfo_TaskResponse `xml:"urn:vim25 QueryVirtualDiskInfo_TaskResponse,omitempty"`
InternalRes *QueryVirtualDiskInfo_TaskResponse `xml:"urn:internalvim25 QueryVirtualDiskInfo_TaskResponse,omitempty"`
Fault_ *soap.Fault `xml:"http://schemas.xmlsoap.org/soap/envelope/ Fault,omitempty"`
}
func (b *QueryVirtualDiskInfoTaskBody) Fault() *soap.Fault { return b.Fault_ }
func QueryVirtualDiskInfoTask(ctx context.Context, r soap.RoundTripper, req *QueryVirtualDiskInfoTaskRequest) (*QueryVirtualDiskInfo_TaskResponse, error) {
var reqBody, resBody QueryVirtualDiskInfoTaskBody
reqBody.Req = req
if err := r.RoundTrip(ctx, &reqBody, &resBody); err != nil {
return nil, err
}
if resBody.Res != nil {
return resBody.Res, nil
}
return resBody.InternalRes, 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/vmware/govmomi/internal/helpers.go | vendor/github.com/vmware/govmomi/internal/helpers.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package internal
import (
"context"
"encoding/xml"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"path"
"slices"
"strings"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/soap"
"github.com/vmware/govmomi/vim25/types"
)
const (
vCenterHostGatewaySocket = "/var/run/envoy-hgw/hgw-pipe"
vCenterHostGatewaySocketEnv = "VCENTER_ENVOY_HOST_GATEWAY"
)
// InventoryPath composed of entities by Name
func InventoryPath(entities []mo.ManagedEntity) string {
val := "/"
for _, entity := range entities {
// Skip root folder in building inventory path.
if entity.Parent == nil {
continue
}
val = path.Join(val, entity.Name)
}
return val
}
var vsanFS = []string{
string(types.HostFileSystemVolumeFileSystemTypeVsan),
string(types.HostFileSystemVolumeFileSystemTypeVVOL),
}
func IsDatastoreVSAN(ds mo.Datastore) bool {
return slices.Contains(vsanFS, ds.Summary.Type)
}
func HostSystemManagementIPs(config []types.VirtualNicManagerNetConfig) []net.IP {
var ips []net.IP
for _, nc := range config {
if nc.NicType != string(types.HostVirtualNicManagerNicTypeManagement) {
continue
}
for ix := range nc.CandidateVnic {
for _, selectedVnicKey := range nc.SelectedVnic {
if nc.CandidateVnic[ix].Key != selectedVnicKey {
continue
}
ip := net.ParseIP(nc.CandidateVnic[ix].Spec.Ip.IpAddress)
if ip != nil {
ips = append(ips, ip)
}
}
}
}
return ips
}
// UsingEnvoySidecar determines if the given *vim25.Client is using vCenter's
// local Envoy sidecar (as opposed to using the HTTPS port.)
// Returns a boolean indicating whether to use the sidecar or not.
func UsingEnvoySidecar(c *vim25.Client) bool {
envoySidecarPort := os.Getenv("GOVMOMI_ENVOY_SIDECAR_PORT")
if envoySidecarPort == "" {
envoySidecarPort = "1080"
}
envoySidecarHost := os.Getenv("GOVMOMI_ENVOY_SIDECAR_HOST")
if envoySidecarHost == "" {
envoySidecarHost = "localhost"
}
return c.URL().Hostname() == envoySidecarHost && c.URL().Scheme == "http" && c.URL().Port() == envoySidecarPort
}
// ClientWithEnvoyHostGateway clones the provided soap.Client and returns a new
// one that uses a Unix socket to leverage vCenter's local Envoy host
// gateway.
// This should be used to construct clients that talk to ESX.
// This method returns a new *vim25.Client and does not modify the original input.
// This client disables HTTP keep alives and is intended for a single round
// trip. (eg. guest file transfer, datastore file transfer)
func ClientWithEnvoyHostGateway(vc *vim25.Client) *vim25.Client {
// Override the vim client with a new one that wraps a Unix socket transport.
// Using HTTP here so secure means nothing.
sc := soap.NewClient(vc.URL(), true)
// Clone the underlying HTTP transport, only replacing the dialer logic.
transport := sc.DefaultTransport().Clone()
hostGatewaySocketPath := os.Getenv(vCenterHostGatewaySocketEnv)
if hostGatewaySocketPath == "" {
hostGatewaySocketPath = vCenterHostGatewaySocket
}
transport.DialContext = func(_ context.Context, _, _ string) (net.Conn, error) {
return net.Dial("unix", hostGatewaySocketPath)
}
// We use this client for a single request, so we don't require keepalives.
transport.DisableKeepAlives = true
sc.Client = http.Client{
Transport: transport,
}
newVC := &vim25.Client{
Client: sc,
}
return newVC
}
// HostGatewayTransferURL rewrites the provided URL to be suitable for use
// with the Envoy host gateway on vCenter.
// It returns a copy of the provided URL with the host, scheme rewritten as needed.
// Receivers of such URLs must typically also use ClientWithEnvoyHostGateway to
// use the appropriate http.Transport to be able to make use of the host
// gateway.
// nil input yields an uninitialized struct.
func HostGatewayTransferURL(u *url.URL, hostMoref types.ManagedObjectReference) *url.URL {
if u == nil {
return &url.URL{}
}
// Make a copy of the provided URL.
turl := *u
turl.Host = "localhost"
turl.Scheme = "http"
oldPath := turl.Path
turl.Path = fmt.Sprintf("/hgw/%s%s", hostMoref.Value, oldPath)
return &turl
}
func (arg ReflectManagedMethodExecuterSoapArgument) Value() []string {
if arg.Val == "" {
return nil
}
d := xml.NewDecoder(strings.NewReader(arg.Val))
var val []string
for {
t, err := d.Token()
if err != nil {
if err == io.EOF {
break
}
panic(err)
}
if c, ok := t.(xml.CharData); ok {
val = append(val, string(c))
}
}
return val
}
func EsxcliName(name string) string {
return strings.ReplaceAll(strings.Title(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/vmware/govmomi/internal/version/version.go | vendor/github.com/vmware/govmomi/internal/version/version.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package version
const (
// ClientName is the name of this SDK
ClientName = "govmomi"
// ClientVersion is the version of this SDK
ClientVersion = "0.50.0"
)
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/task/error.go | vendor/github.com/vmware/govmomi/task/error.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package task
import "github.com/vmware/govmomi/vim25/types"
type Error struct {
*types.LocalizedMethodFault
Description *types.LocalizableMessage
}
// Error returns the task's localized fault message.
func (e Error) Error() string {
return e.LocalizedMethodFault.LocalizedMessage
}
func (e Error) Fault() types.BaseMethodFault {
return e.LocalizedMethodFault.Fault
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/vmware/govmomi/task/wait.go | vendor/github.com/vmware/govmomi/task/wait.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package task
import (
"context"
"github.com/vmware/govmomi/property"
"github.com/vmware/govmomi/vim25/progress"
"github.com/vmware/govmomi/vim25/types"
)
type taskProgress struct {
info *types.TaskInfo
}
func (t taskProgress) Percentage() float32 {
return float32(t.info.Progress)
}
func (t taskProgress) Detail() string {
return ""
}
func (t taskProgress) Error() error {
if t.info.Error != nil {
return Error{t.info.Error, t.info.Description}
}
return nil
}
type taskCallback struct {
ch chan<- progress.Report
info *types.TaskInfo
err error
}
func (t *taskCallback) fn(pc []types.PropertyChange) bool {
for _, c := range pc {
if c.Name != "info" {
continue
}
if c.Op != types.PropertyChangeOpAssign {
continue
}
if c.Val == nil {
continue
}
ti := c.Val.(types.TaskInfo)
t.info = &ti
}
// t.info could be nil if pc can't satisfy the rules above
if t.info == nil {
return false
}
pr := taskProgress{t.info}
// Store copy of error, so Wait() can return it as well.
t.err = pr.Error()
switch t.info.State {
case types.TaskInfoStateQueued, types.TaskInfoStateRunning:
if t.ch != nil {
// Don't care if this is dropped
select {
case t.ch <- pr:
default:
}
}
return false
case types.TaskInfoStateSuccess, types.TaskInfoStateError:
if t.ch != nil {
// Last one must always be delivered
t.ch <- pr
}
return true
default:
panic("unknown state: " + t.info.State)
}
}
// WaitEx waits for a task to finish with either success or failure. It does so
// by waiting for the "info" property of task managed object to change. The
// function returns when it finds the task in the "success" or "error" state.
// In the former case, the return value is nil. In the latter case the return
// value is an instance of this package's Error struct.
//
// Any error returned while waiting for property changes causes the function to
// return immediately and propagate the error.
//
// If the progress.Sinker argument is specified, any progress updates for the
// task are sent here. The completion percentage is passed through directly.
// The detail for the progress update is set to an empty string. If the task
// finishes in the error state, the error instance is passed through as well.
// Note that this error is the same error that is returned by this function.
func WaitEx(
ctx context.Context,
ref types.ManagedObjectReference,
pc *property.Collector,
s progress.Sinker) (*types.TaskInfo, error) {
cb := &taskCallback{}
// Include progress sink if specified
if s != nil {
cb.ch = s.Sink()
defer close(cb.ch)
}
filter := &property.WaitFilter{
WaitOptions: property.WaitOptions{
PropagateMissing: true,
},
}
filter.Add(ref, ref.Type, []string{"info"})
if err := property.WaitForUpdatesEx(
ctx,
pc,
filter,
func(updates []types.ObjectUpdate) bool {
for _, update := range updates {
// Only look at updates for the expected task object.
if update.Obj.Value == ref.Value && update.Obj.Type == ref.Type {
if cb.fn(update.ChangeSet) {
return true
}
}
}
return false
}); err != nil {
return nil, err
}
return cb.info, cb.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/vmware/govmomi/task/history_collector.go | vendor/github.com/vmware/govmomi/task/history_collector.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package task
import (
"context"
"github.com/vmware/govmomi/history"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/mo"
"github.com/vmware/govmomi/vim25/types"
)
// HistoryCollector provides a mechanism for retrieving historical data and
// updates when the server appends new tasks.
type HistoryCollector struct {
*history.Collector
}
func newHistoryCollector(c *vim25.Client, ref types.ManagedObjectReference) *HistoryCollector {
return &HistoryCollector{
Collector: history.NewCollector(c, ref),
}
}
// LatestPage returns items in the 'viewable latest page' of the task history collector.
// As new tasks that match the collector's TaskFilterSpec are created,
// they are added to this page, and the oldest tasks are removed from the collector to keep
// the size of the page to that allowed by SetCollectorPageSize.
// The "oldest task" is the one with the oldest creation time. The tasks in the returned page are unordered.
func (h HistoryCollector) LatestPage(ctx context.Context) ([]types.TaskInfo, error) {
var o mo.TaskHistoryCollector
err := h.Properties(ctx, h.Reference(), []string{"latestPage"}, &o)
if err != nil {
return nil, err
}
return o.LatestPage, nil
}
// ReadNextTasks reads the scrollable view from the current position. The
// scrollable position is moved to the next newer page after the read. No item
// is returned when the end of the collector is reached.
func (h HistoryCollector) ReadNextTasks(ctx context.Context, maxCount int32) ([]types.TaskInfo, error) {
req := types.ReadNextTasks{
This: h.Reference(),
MaxCount: maxCount,
}
res, err := methods.ReadNextTasks(ctx, h.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}
// ReadPreviousTasks reads the scrollable view from the current position. The
// scrollable position is then moved to the next older page after the read. No
// item is returned when the head of the collector is reached.
func (h HistoryCollector) ReadPreviousTasks(ctx context.Context, maxCount int32) ([]types.TaskInfo, error) {
req := types.ReadPreviousTasks{
This: h.Reference(),
MaxCount: maxCount,
}
res, err := methods.ReadPreviousTasks(ctx, h.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, 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/vmware/govmomi/task/manager.go | vendor/github.com/vmware/govmomi/task/manager.go | // © Broadcom. All Rights Reserved.
// The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
// SPDX-License-Identifier: Apache-2.0
package task
import (
"context"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/methods"
"github.com/vmware/govmomi/vim25/types"
)
type Manager struct {
r types.ManagedObjectReference
c *vim25.Client
}
// NewManager creates a new task manager
func NewManager(c *vim25.Client) *Manager {
m := Manager{
r: *c.ServiceContent.TaskManager,
c: c,
}
return &m
}
// Reference returns the task.Manager MOID
func (m Manager) Reference() types.ManagedObjectReference {
return m.r
}
// CreateCollectorForTasks returns a task history collector, a specialized
// history collector that gathers TaskInfo data objects.
func (m Manager) CreateCollectorForTasks(ctx context.Context, filter types.TaskFilterSpec) (*HistoryCollector, error) {
req := types.CreateCollectorForTasks{
This: m.r,
Filter: filter,
}
res, err := methods.CreateCollectorForTasks(ctx, m.c, &req)
if err != nil {
return nil, err
}
return newHistoryCollector(m.c, res.Returnval), 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/spf13/cast/caste.go | vendor/github.com/spf13/cast/caste.go | // Copyright © 2014 Steve Francia <spf@spf13.com>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package cast
import (
"encoding/json"
"errors"
"fmt"
"html/template"
"reflect"
"strconv"
"strings"
"time"
)
var errNegativeNotAllowed = errors.New("unable to cast negative value")
type float64EProvider interface {
Float64() (float64, error)
}
type float64Provider interface {
Float64() float64
}
// ToTimeE casts an interface to a time.Time type.
func ToTimeE(i interface{}) (tim time.Time, err error) {
return ToTimeInDefaultLocationE(i, time.UTC)
}
// ToTimeInDefaultLocationE casts an empty interface to time.Time,
// interpreting inputs without a timezone to be in the given location,
// or the local timezone if nil.
func ToTimeInDefaultLocationE(i interface{}, location *time.Location) (tim time.Time, err error) {
i = indirect(i)
switch v := i.(type) {
case time.Time:
return v, nil
case string:
return StringToDateInDefaultLocation(v, location)
case json.Number:
s, err1 := ToInt64E(v)
if err1 != nil {
return time.Time{}, fmt.Errorf("unable to cast %#v of type %T to Time", i, i)
}
return time.Unix(s, 0), nil
case int:
return time.Unix(int64(v), 0), nil
case int64:
return time.Unix(v, 0), nil
case int32:
return time.Unix(int64(v), 0), nil
case uint:
return time.Unix(int64(v), 0), nil
case uint64:
return time.Unix(int64(v), 0), nil
case uint32:
return time.Unix(int64(v), 0), nil
default:
return time.Time{}, fmt.Errorf("unable to cast %#v of type %T to Time", i, i)
}
}
// ToDurationE casts an interface to a time.Duration type.
func ToDurationE(i interface{}) (d time.Duration, err error) {
i = indirect(i)
switch s := i.(type) {
case time.Duration:
return s, nil
case int, int64, int32, int16, int8, uint, uint64, uint32, uint16, uint8:
d = time.Duration(ToInt64(s))
return
case float32, float64:
d = time.Duration(ToFloat64(s))
return
case string:
if strings.ContainsAny(s, "nsuµmh") {
d, err = time.ParseDuration(s)
} else {
d, err = time.ParseDuration(s + "ns")
}
return
case float64EProvider:
var v float64
v, err = s.Float64()
d = time.Duration(v)
return
case float64Provider:
d = time.Duration(s.Float64())
return
default:
err = fmt.Errorf("unable to cast %#v of type %T to Duration", i, i)
return
}
}
// ToBoolE casts an interface to a bool type.
func ToBoolE(i interface{}) (bool, error) {
i = indirect(i)
switch b := i.(type) {
case bool:
return b, nil
case nil:
return false, nil
case int:
return b != 0, nil
case int64:
return b != 0, nil
case int32:
return b != 0, nil
case int16:
return b != 0, nil
case int8:
return b != 0, nil
case uint:
return b != 0, nil
case uint64:
return b != 0, nil
case uint32:
return b != 0, nil
case uint16:
return b != 0, nil
case uint8:
return b != 0, nil
case float64:
return b != 0, nil
case float32:
return b != 0, nil
case time.Duration:
return b != 0, nil
case string:
return strconv.ParseBool(i.(string))
case json.Number:
v, err := ToInt64E(b)
if err == nil {
return v != 0, nil
}
return false, fmt.Errorf("unable to cast %#v of type %T to bool", i, i)
default:
return false, fmt.Errorf("unable to cast %#v of type %T to bool", i, i)
}
}
// ToFloat64E casts an interface to a float64 type.
func ToFloat64E(i interface{}) (float64, error) {
i = indirect(i)
intv, ok := toInt(i)
if ok {
return float64(intv), nil
}
switch s := i.(type) {
case float64:
return s, nil
case float32:
return float64(s), nil
case int64:
return float64(s), nil
case int32:
return float64(s), nil
case int16:
return float64(s), nil
case int8:
return float64(s), nil
case uint:
return float64(s), nil
case uint64:
return float64(s), nil
case uint32:
return float64(s), nil
case uint16:
return float64(s), nil
case uint8:
return float64(s), nil
case string:
v, err := strconv.ParseFloat(s, 64)
if err == nil {
return v, nil
}
return 0, fmt.Errorf("unable to cast %#v of type %T to float64", i, i)
case float64EProvider:
v, err := s.Float64()
if err == nil {
return v, nil
}
return 0, fmt.Errorf("unable to cast %#v of type %T to float64", i, i)
case float64Provider:
return s.Float64(), nil
case bool:
if s {
return 1, nil
}
return 0, nil
case nil:
return 0, nil
default:
return 0, fmt.Errorf("unable to cast %#v of type %T to float64", i, i)
}
}
// ToFloat32E casts an interface to a float32 type.
func ToFloat32E(i interface{}) (float32, error) {
i = indirect(i)
intv, ok := toInt(i)
if ok {
return float32(intv), nil
}
switch s := i.(type) {
case float64:
return float32(s), nil
case float32:
return s, nil
case int64:
return float32(s), nil
case int32:
return float32(s), nil
case int16:
return float32(s), nil
case int8:
return float32(s), nil
case uint:
return float32(s), nil
case uint64:
return float32(s), nil
case uint32:
return float32(s), nil
case uint16:
return float32(s), nil
case uint8:
return float32(s), nil
case string:
v, err := strconv.ParseFloat(s, 32)
if err == nil {
return float32(v), nil
}
return 0, fmt.Errorf("unable to cast %#v of type %T to float32", i, i)
case float64EProvider:
v, err := s.Float64()
if err == nil {
return float32(v), nil
}
return 0, fmt.Errorf("unable to cast %#v of type %T to float32", i, i)
case float64Provider:
return float32(s.Float64()), nil
case bool:
if s {
return 1, nil
}
return 0, nil
case nil:
return 0, nil
default:
return 0, fmt.Errorf("unable to cast %#v of type %T to float32", i, i)
}
}
// ToInt64E casts an interface to an int64 type.
func ToInt64E(i interface{}) (int64, error) {
i = indirect(i)
intv, ok := toInt(i)
if ok {
return int64(intv), nil
}
switch s := i.(type) {
case int64:
return s, nil
case int32:
return int64(s), nil
case int16:
return int64(s), nil
case int8:
return int64(s), nil
case uint:
return int64(s), nil
case uint64:
return int64(s), nil
case uint32:
return int64(s), nil
case uint16:
return int64(s), nil
case uint8:
return int64(s), nil
case float64:
return int64(s), nil
case float32:
return int64(s), nil
case string:
v, err := strconv.ParseInt(trimZeroDecimal(s), 0, 0)
if err == nil {
return v, nil
}
return 0, fmt.Errorf("unable to cast %#v of type %T to int64", i, i)
case json.Number:
return ToInt64E(string(s))
case bool:
if s {
return 1, nil
}
return 0, nil
case nil:
return 0, nil
default:
return 0, fmt.Errorf("unable to cast %#v of type %T to int64", i, i)
}
}
// ToInt32E casts an interface to an int32 type.
func ToInt32E(i interface{}) (int32, error) {
i = indirect(i)
intv, ok := toInt(i)
if ok {
return int32(intv), nil
}
switch s := i.(type) {
case int64:
return int32(s), nil
case int32:
return s, nil
case int16:
return int32(s), nil
case int8:
return int32(s), nil
case uint:
return int32(s), nil
case uint64:
return int32(s), nil
case uint32:
return int32(s), nil
case uint16:
return int32(s), nil
case uint8:
return int32(s), nil
case float64:
return int32(s), nil
case float32:
return int32(s), nil
case string:
v, err := strconv.ParseInt(trimZeroDecimal(s), 0, 0)
if err == nil {
return int32(v), nil
}
return 0, fmt.Errorf("unable to cast %#v of type %T to int32", i, i)
case json.Number:
return ToInt32E(string(s))
case bool:
if s {
return 1, nil
}
return 0, nil
case nil:
return 0, nil
default:
return 0, fmt.Errorf("unable to cast %#v of type %T to int32", i, i)
}
}
// ToInt16E casts an interface to an int16 type.
func ToInt16E(i interface{}) (int16, error) {
i = indirect(i)
intv, ok := toInt(i)
if ok {
return int16(intv), nil
}
switch s := i.(type) {
case int64:
return int16(s), nil
case int32:
return int16(s), nil
case int16:
return s, nil
case int8:
return int16(s), nil
case uint:
return int16(s), nil
case uint64:
return int16(s), nil
case uint32:
return int16(s), nil
case uint16:
return int16(s), nil
case uint8:
return int16(s), nil
case float64:
return int16(s), nil
case float32:
return int16(s), nil
case string:
v, err := strconv.ParseInt(trimZeroDecimal(s), 0, 0)
if err == nil {
return int16(v), nil
}
return 0, fmt.Errorf("unable to cast %#v of type %T to int16", i, i)
case json.Number:
return ToInt16E(string(s))
case bool:
if s {
return 1, nil
}
return 0, nil
case nil:
return 0, nil
default:
return 0, fmt.Errorf("unable to cast %#v of type %T to int16", i, i)
}
}
// ToInt8E casts an interface to an int8 type.
func ToInt8E(i interface{}) (int8, error) {
i = indirect(i)
intv, ok := toInt(i)
if ok {
return int8(intv), nil
}
switch s := i.(type) {
case int64:
return int8(s), nil
case int32:
return int8(s), nil
case int16:
return int8(s), nil
case int8:
return s, nil
case uint:
return int8(s), nil
case uint64:
return int8(s), nil
case uint32:
return int8(s), nil
case uint16:
return int8(s), nil
case uint8:
return int8(s), nil
case float64:
return int8(s), nil
case float32:
return int8(s), nil
case string:
v, err := strconv.ParseInt(trimZeroDecimal(s), 0, 0)
if err == nil {
return int8(v), nil
}
return 0, fmt.Errorf("unable to cast %#v of type %T to int8", i, i)
case json.Number:
return ToInt8E(string(s))
case bool:
if s {
return 1, nil
}
return 0, nil
case nil:
return 0, nil
default:
return 0, fmt.Errorf("unable to cast %#v of type %T to int8", i, i)
}
}
// ToIntE casts an interface to an int type.
func ToIntE(i interface{}) (int, error) {
i = indirect(i)
intv, ok := toInt(i)
if ok {
return intv, nil
}
switch s := i.(type) {
case int64:
return int(s), nil
case int32:
return int(s), nil
case int16:
return int(s), nil
case int8:
return int(s), nil
case uint:
return int(s), nil
case uint64:
return int(s), nil
case uint32:
return int(s), nil
case uint16:
return int(s), nil
case uint8:
return int(s), nil
case float64:
return int(s), nil
case float32:
return int(s), nil
case string:
v, err := strconv.ParseInt(trimZeroDecimal(s), 0, 0)
if err == nil {
return int(v), nil
}
return 0, fmt.Errorf("unable to cast %#v of type %T to int64", i, i)
case json.Number:
return ToIntE(string(s))
case bool:
if s {
return 1, nil
}
return 0, nil
case nil:
return 0, nil
default:
return 0, fmt.Errorf("unable to cast %#v of type %T to int", i, i)
}
}
// ToUintE casts an interface to a uint type.
func ToUintE(i interface{}) (uint, error) {
i = indirect(i)
intv, ok := toInt(i)
if ok {
if intv < 0 {
return 0, errNegativeNotAllowed
}
return uint(intv), nil
}
switch s := i.(type) {
case string:
v, err := strconv.ParseInt(trimZeroDecimal(s), 0, 0)
if err == nil {
if v < 0 {
return 0, errNegativeNotAllowed
}
return uint(v), nil
}
return 0, fmt.Errorf("unable to cast %#v of type %T to uint", i, i)
case json.Number:
return ToUintE(string(s))
case int64:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint(s), nil
case int32:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint(s), nil
case int16:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint(s), nil
case int8:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint(s), nil
case uint:
return s, nil
case uint64:
return uint(s), nil
case uint32:
return uint(s), nil
case uint16:
return uint(s), nil
case uint8:
return uint(s), nil
case float64:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint(s), nil
case float32:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint(s), nil
case bool:
if s {
return 1, nil
}
return 0, nil
case nil:
return 0, nil
default:
return 0, fmt.Errorf("unable to cast %#v of type %T to uint", i, i)
}
}
// ToUint64E casts an interface to a uint64 type.
func ToUint64E(i interface{}) (uint64, error) {
i = indirect(i)
intv, ok := toInt(i)
if ok {
if intv < 0 {
return 0, errNegativeNotAllowed
}
return uint64(intv), nil
}
switch s := i.(type) {
case string:
v, err := strconv.ParseInt(trimZeroDecimal(s), 0, 0)
if err == nil {
if v < 0 {
return 0, errNegativeNotAllowed
}
return uint64(v), nil
}
return 0, fmt.Errorf("unable to cast %#v of type %T to uint64", i, i)
case json.Number:
return ToUint64E(string(s))
case int64:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint64(s), nil
case int32:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint64(s), nil
case int16:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint64(s), nil
case int8:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint64(s), nil
case uint:
return uint64(s), nil
case uint64:
return s, nil
case uint32:
return uint64(s), nil
case uint16:
return uint64(s), nil
case uint8:
return uint64(s), nil
case float32:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint64(s), nil
case float64:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint64(s), nil
case bool:
if s {
return 1, nil
}
return 0, nil
case nil:
return 0, nil
default:
return 0, fmt.Errorf("unable to cast %#v of type %T to uint64", i, i)
}
}
// ToUint32E casts an interface to a uint32 type.
func ToUint32E(i interface{}) (uint32, error) {
i = indirect(i)
intv, ok := toInt(i)
if ok {
if intv < 0 {
return 0, errNegativeNotAllowed
}
return uint32(intv), nil
}
switch s := i.(type) {
case string:
v, err := strconv.ParseInt(trimZeroDecimal(s), 0, 0)
if err == nil {
if v < 0 {
return 0, errNegativeNotAllowed
}
return uint32(v), nil
}
return 0, fmt.Errorf("unable to cast %#v of type %T to uint32", i, i)
case json.Number:
return ToUint32E(string(s))
case int64:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint32(s), nil
case int32:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint32(s), nil
case int16:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint32(s), nil
case int8:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint32(s), nil
case uint:
return uint32(s), nil
case uint64:
return uint32(s), nil
case uint32:
return s, nil
case uint16:
return uint32(s), nil
case uint8:
return uint32(s), nil
case float64:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint32(s), nil
case float32:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint32(s), nil
case bool:
if s {
return 1, nil
}
return 0, nil
case nil:
return 0, nil
default:
return 0, fmt.Errorf("unable to cast %#v of type %T to uint32", i, i)
}
}
// ToUint16E casts an interface to a uint16 type.
func ToUint16E(i interface{}) (uint16, error) {
i = indirect(i)
intv, ok := toInt(i)
if ok {
if intv < 0 {
return 0, errNegativeNotAllowed
}
return uint16(intv), nil
}
switch s := i.(type) {
case string:
v, err := strconv.ParseInt(trimZeroDecimal(s), 0, 0)
if err == nil {
if v < 0 {
return 0, errNegativeNotAllowed
}
return uint16(v), nil
}
return 0, fmt.Errorf("unable to cast %#v of type %T to uint16", i, i)
case json.Number:
return ToUint16E(string(s))
case int64:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint16(s), nil
case int32:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint16(s), nil
case int16:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint16(s), nil
case int8:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint16(s), nil
case uint:
return uint16(s), nil
case uint64:
return uint16(s), nil
case uint32:
return uint16(s), nil
case uint16:
return s, nil
case uint8:
return uint16(s), nil
case float64:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint16(s), nil
case float32:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint16(s), nil
case bool:
if s {
return 1, nil
}
return 0, nil
case nil:
return 0, nil
default:
return 0, fmt.Errorf("unable to cast %#v of type %T to uint16", i, i)
}
}
// ToUint8E casts an interface to a uint type.
func ToUint8E(i interface{}) (uint8, error) {
i = indirect(i)
intv, ok := toInt(i)
if ok {
if intv < 0 {
return 0, errNegativeNotAllowed
}
return uint8(intv), nil
}
switch s := i.(type) {
case string:
v, err := strconv.ParseInt(trimZeroDecimal(s), 0, 0)
if err == nil {
if v < 0 {
return 0, errNegativeNotAllowed
}
return uint8(v), nil
}
return 0, fmt.Errorf("unable to cast %#v of type %T to uint8", i, i)
case json.Number:
return ToUint8E(string(s))
case int64:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint8(s), nil
case int32:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint8(s), nil
case int16:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint8(s), nil
case int8:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint8(s), nil
case uint:
return uint8(s), nil
case uint64:
return uint8(s), nil
case uint32:
return uint8(s), nil
case uint16:
return uint8(s), nil
case uint8:
return s, nil
case float64:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint8(s), nil
case float32:
if s < 0 {
return 0, errNegativeNotAllowed
}
return uint8(s), nil
case bool:
if s {
return 1, nil
}
return 0, nil
case nil:
return 0, nil
default:
return 0, fmt.Errorf("unable to cast %#v of type %T to uint8", i, i)
}
}
// From html/template/content.go
// Copyright 2011 The Go Authors. All rights reserved.
// indirect returns the value, after dereferencing as many times
// as necessary to reach the base type (or nil).
func indirect(a interface{}) interface{} {
if a == nil {
return nil
}
if t := reflect.TypeOf(a); t.Kind() != reflect.Ptr {
// Avoid creating a reflect.Value if it's not a pointer.
return a
}
v := reflect.ValueOf(a)
for v.Kind() == reflect.Ptr && !v.IsNil() {
v = v.Elem()
}
return v.Interface()
}
// From html/template/content.go
// Copyright 2011 The Go Authors. All rights reserved.
// indirectToStringerOrError returns the value, after dereferencing as many times
// as necessary to reach the base type (or nil) or an implementation of fmt.Stringer
// or error,
func indirectToStringerOrError(a interface{}) interface{} {
if a == nil {
return nil
}
errorType := reflect.TypeOf((*error)(nil)).Elem()
fmtStringerType := reflect.TypeOf((*fmt.Stringer)(nil)).Elem()
v := reflect.ValueOf(a)
for !v.Type().Implements(fmtStringerType) && !v.Type().Implements(errorType) && v.Kind() == reflect.Ptr && !v.IsNil() {
v = v.Elem()
}
return v.Interface()
}
// ToStringE casts an interface to a string type.
func ToStringE(i interface{}) (string, error) {
i = indirectToStringerOrError(i)
switch s := i.(type) {
case string:
return s, nil
case bool:
return strconv.FormatBool(s), nil
case float64:
return strconv.FormatFloat(s, 'f', -1, 64), nil
case float32:
return strconv.FormatFloat(float64(s), 'f', -1, 32), nil
case int:
return strconv.Itoa(s), nil
case int64:
return strconv.FormatInt(s, 10), nil
case int32:
return strconv.Itoa(int(s)), nil
case int16:
return strconv.FormatInt(int64(s), 10), nil
case int8:
return strconv.FormatInt(int64(s), 10), nil
case uint:
return strconv.FormatUint(uint64(s), 10), nil
case uint64:
return strconv.FormatUint(uint64(s), 10), nil
case uint32:
return strconv.FormatUint(uint64(s), 10), nil
case uint16:
return strconv.FormatUint(uint64(s), 10), nil
case uint8:
return strconv.FormatUint(uint64(s), 10), nil
case json.Number:
return s.String(), nil
case []byte:
return string(s), nil
case template.HTML:
return string(s), nil
case template.URL:
return string(s), nil
case template.JS:
return string(s), nil
case template.CSS:
return string(s), nil
case template.HTMLAttr:
return string(s), nil
case nil:
return "", nil
case fmt.Stringer:
return s.String(), nil
case error:
return s.Error(), nil
default:
return "", fmt.Errorf("unable to cast %#v of type %T to string", i, i)
}
}
// ToStringMapStringE casts an interface to a map[string]string type.
func ToStringMapStringE(i interface{}) (map[string]string, error) {
m := map[string]string{}
switch v := i.(type) {
case map[string]string:
return v, nil
case map[string]interface{}:
for k, val := range v {
m[ToString(k)] = ToString(val)
}
return m, nil
case map[interface{}]string:
for k, val := range v {
m[ToString(k)] = ToString(val)
}
return m, nil
case map[interface{}]interface{}:
for k, val := range v {
m[ToString(k)] = ToString(val)
}
return m, nil
case string:
err := jsonStringToObject(v, &m)
return m, err
default:
return m, fmt.Errorf("unable to cast %#v of type %T to map[string]string", i, i)
}
}
// ToStringMapStringSliceE casts an interface to a map[string][]string type.
func ToStringMapStringSliceE(i interface{}) (map[string][]string, error) {
m := map[string][]string{}
switch v := i.(type) {
case map[string][]string:
return v, nil
case map[string][]interface{}:
for k, val := range v {
m[ToString(k)] = ToStringSlice(val)
}
return m, nil
case map[string]string:
for k, val := range v {
m[ToString(k)] = []string{val}
}
case map[string]interface{}:
for k, val := range v {
switch vt := val.(type) {
case []interface{}:
m[ToString(k)] = ToStringSlice(vt)
case []string:
m[ToString(k)] = vt
default:
m[ToString(k)] = []string{ToString(val)}
}
}
return m, nil
case map[interface{}][]string:
for k, val := range v {
m[ToString(k)] = ToStringSlice(val)
}
return m, nil
case map[interface{}]string:
for k, val := range v {
m[ToString(k)] = ToStringSlice(val)
}
return m, nil
case map[interface{}][]interface{}:
for k, val := range v {
m[ToString(k)] = ToStringSlice(val)
}
return m, nil
case map[interface{}]interface{}:
for k, val := range v {
key, err := ToStringE(k)
if err != nil {
return m, fmt.Errorf("unable to cast %#v of type %T to map[string][]string", i, i)
}
value, err := ToStringSliceE(val)
if err != nil {
return m, fmt.Errorf("unable to cast %#v of type %T to map[string][]string", i, i)
}
m[key] = value
}
case string:
err := jsonStringToObject(v, &m)
return m, err
default:
return m, fmt.Errorf("unable to cast %#v of type %T to map[string][]string", i, i)
}
return m, nil
}
// ToStringMapBoolE casts an interface to a map[string]bool type.
func ToStringMapBoolE(i interface{}) (map[string]bool, error) {
m := map[string]bool{}
switch v := i.(type) {
case map[interface{}]interface{}:
for k, val := range v {
m[ToString(k)] = ToBool(val)
}
return m, nil
case map[string]interface{}:
for k, val := range v {
m[ToString(k)] = ToBool(val)
}
return m, nil
case map[string]bool:
return v, nil
case string:
err := jsonStringToObject(v, &m)
return m, err
default:
return m, fmt.Errorf("unable to cast %#v of type %T to map[string]bool", i, i)
}
}
// ToStringMapE casts an interface to a map[string]interface{} type.
func ToStringMapE(i interface{}) (map[string]interface{}, error) {
m := map[string]interface{}{}
switch v := i.(type) {
case map[interface{}]interface{}:
for k, val := range v {
m[ToString(k)] = val
}
return m, nil
case map[string]interface{}:
return v, nil
case string:
err := jsonStringToObject(v, &m)
return m, err
default:
return m, fmt.Errorf("unable to cast %#v of type %T to map[string]interface{}", i, i)
}
}
// ToStringMapIntE casts an interface to a map[string]int{} type.
func ToStringMapIntE(i interface{}) (map[string]int, error) {
m := map[string]int{}
if i == nil {
return m, fmt.Errorf("unable to cast %#v of type %T to map[string]int", i, i)
}
switch v := i.(type) {
case map[interface{}]interface{}:
for k, val := range v {
m[ToString(k)] = ToInt(val)
}
return m, nil
case map[string]interface{}:
for k, val := range v {
m[k] = ToInt(val)
}
return m, nil
case map[string]int:
return v, nil
case string:
err := jsonStringToObject(v, &m)
return m, err
}
if reflect.TypeOf(i).Kind() != reflect.Map {
return m, fmt.Errorf("unable to cast %#v of type %T to map[string]int", i, i)
}
mVal := reflect.ValueOf(m)
v := reflect.ValueOf(i)
for _, keyVal := range v.MapKeys() {
val, err := ToIntE(v.MapIndex(keyVal).Interface())
if err != nil {
return m, fmt.Errorf("unable to cast %#v of type %T to map[string]int", i, i)
}
mVal.SetMapIndex(keyVal, reflect.ValueOf(val))
}
return m, nil
}
// ToStringMapInt64E casts an interface to a map[string]int64{} type.
func ToStringMapInt64E(i interface{}) (map[string]int64, error) {
m := map[string]int64{}
if i == nil {
return m, fmt.Errorf("unable to cast %#v of type %T to map[string]int64", i, i)
}
switch v := i.(type) {
case map[interface{}]interface{}:
for k, val := range v {
m[ToString(k)] = ToInt64(val)
}
return m, nil
case map[string]interface{}:
for k, val := range v {
m[k] = ToInt64(val)
}
return m, nil
case map[string]int64:
return v, nil
case string:
err := jsonStringToObject(v, &m)
return m, err
}
if reflect.TypeOf(i).Kind() != reflect.Map {
return m, fmt.Errorf("unable to cast %#v of type %T to map[string]int64", i, i)
}
mVal := reflect.ValueOf(m)
v := reflect.ValueOf(i)
for _, keyVal := range v.MapKeys() {
val, err := ToInt64E(v.MapIndex(keyVal).Interface())
if err != nil {
return m, fmt.Errorf("unable to cast %#v of type %T to map[string]int64", i, i)
}
mVal.SetMapIndex(keyVal, reflect.ValueOf(val))
}
return m, nil
}
// ToSliceE casts an interface to a []interface{} type.
func ToSliceE(i interface{}) ([]interface{}, error) {
var s []interface{}
switch v := i.(type) {
case []interface{}:
return append(s, v...), nil
case []map[string]interface{}:
for _, u := range v {
s = append(s, u)
}
return s, nil
default:
return s, fmt.Errorf("unable to cast %#v of type %T to []interface{}", i, i)
}
}
// ToBoolSliceE casts an interface to a []bool type.
func ToBoolSliceE(i interface{}) ([]bool, error) {
if i == nil {
return []bool{}, fmt.Errorf("unable to cast %#v of type %T to []bool", i, i)
}
switch v := i.(type) {
case []bool:
return v, nil
}
kind := reflect.TypeOf(i).Kind()
switch kind {
case reflect.Slice, reflect.Array:
s := reflect.ValueOf(i)
a := make([]bool, s.Len())
for j := 0; j < s.Len(); j++ {
val, err := ToBoolE(s.Index(j).Interface())
if err != nil {
return []bool{}, fmt.Errorf("unable to cast %#v of type %T to []bool", i, i)
}
a[j] = val
}
return a, nil
default:
return []bool{}, fmt.Errorf("unable to cast %#v of type %T to []bool", i, i)
}
}
// ToStringSliceE casts an interface to a []string type.
func ToStringSliceE(i interface{}) ([]string, error) {
var a []string
switch v := i.(type) {
case []interface{}:
for _, u := range v {
a = append(a, ToString(u))
}
return a, nil
case []string:
return v, nil
case []int8:
for _, u := range v {
a = append(a, ToString(u))
}
return a, nil
case []int:
for _, u := range v {
a = append(a, ToString(u))
}
return a, nil
case []int32:
for _, u := range v {
a = append(a, ToString(u))
}
return a, nil
case []int64:
for _, u := range v {
a = append(a, ToString(u))
}
return a, nil
case []float32:
for _, u := range v {
a = append(a, ToString(u))
}
return a, nil
case []float64:
for _, u := range v {
a = append(a, ToString(u))
}
return a, nil
case string:
return strings.Fields(v), nil
case []error:
for _, err := range i.([]error) {
a = append(a, err.Error())
}
return a, nil
case interface{}:
str, err := ToStringE(v)
if err != nil {
return a, fmt.Errorf("unable to cast %#v of type %T to []string", i, i)
}
return []string{str}, nil
default:
return a, fmt.Errorf("unable to cast %#v of type %T to []string", i, i)
}
}
// ToIntSliceE casts an interface to a []int type.
func ToIntSliceE(i interface{}) ([]int, error) {
if i == nil {
return []int{}, fmt.Errorf("unable to cast %#v of type %T to []int", i, i)
}
switch v := i.(type) {
case []int:
return v, nil
}
kind := reflect.TypeOf(i).Kind()
switch kind {
case reflect.Slice, reflect.Array:
s := reflect.ValueOf(i)
a := make([]int, s.Len())
for j := 0; j < s.Len(); j++ {
val, err := ToIntE(s.Index(j).Interface())
if err != nil {
return []int{}, fmt.Errorf("unable to cast %#v of type %T to []int", i, i)
}
a[j] = val
}
return a, nil
default:
return []int{}, fmt.Errorf("unable to cast %#v of type %T to []int", i, i)
}
}
// ToDurationSliceE casts an interface to a []time.Duration type.
func ToDurationSliceE(i interface{}) ([]time.Duration, error) {
if i == nil {
return []time.Duration{}, fmt.Errorf("unable to cast %#v of type %T to []time.Duration", i, i)
}
switch v := i.(type) {
case []time.Duration:
return v, nil
}
kind := reflect.TypeOf(i).Kind()
switch kind {
case reflect.Slice, reflect.Array:
s := reflect.ValueOf(i)
a := make([]time.Duration, s.Len())
for j := 0; j < s.Len(); j++ {
val, err := ToDurationE(s.Index(j).Interface())
if err != nil {
return []time.Duration{}, fmt.Errorf("unable to cast %#v of type %T to []time.Duration", i, i)
}
a[j] = val
}
return a, nil
default:
return []time.Duration{}, fmt.Errorf("unable to cast %#v of type %T to []time.Duration", i, i)
}
}
// StringToDate attempts to parse a string into a time.Time type using a
// predefined list of formats. If no suitable format is found, an error is
// returned.
func StringToDate(s string) (time.Time, error) {
return parseDateWith(s, time.UTC, timeFormats)
}
// StringToDateInDefaultLocation casts an empty interface to a time.Time,
// interpreting inputs without a timezone to be in the given location,
// or the local timezone if nil.
func StringToDateInDefaultLocation(s string, location *time.Location) (time.Time, error) {
return parseDateWith(s, location, timeFormats)
}
type timeFormatType int
const (
timeFormatNoTimezone timeFormatType = iota
timeFormatNamedTimezone
timeFormatNumericTimezone
timeFormatNumericAndNamedTimezone
timeFormatTimeOnly
)
type timeFormat struct {
format string
typ timeFormatType
}
func (f timeFormat) hasTimezone() bool {
// We don't include the formats with only named timezones, see
// https://github.com/golang/go/issues/19694#issuecomment-289103522
return f.typ >= timeFormatNumericTimezone && f.typ <= timeFormatNumericAndNamedTimezone
}
var timeFormats = []timeFormat{
// Keep common formats at the top.
{"2006-01-02", timeFormatNoTimezone},
{time.RFC3339, timeFormatNumericTimezone},
{"2006-01-02T15:04:05", timeFormatNoTimezone}, // iso8601 without timezone
{time.RFC1123Z, timeFormatNumericTimezone},
{time.RFC1123, timeFormatNamedTimezone},
{time.RFC822Z, timeFormatNumericTimezone},
{time.RFC822, timeFormatNamedTimezone},
{time.RFC850, timeFormatNamedTimezone},
{"2006-01-02 15:04:05.999999999 -0700 MST", timeFormatNumericAndNamedTimezone}, // Time.String()
{"2006-01-02T15:04:05-0700", timeFormatNumericTimezone}, // RFC3339 without timezone hh:mm colon
{"2006-01-02 15:04:05Z0700", timeFormatNumericTimezone}, // RFC3339 without T or timezone hh:mm colon
{"2006-01-02 15:04:05", timeFormatNoTimezone},
{time.ANSIC, timeFormatNoTimezone},
{time.UnixDate, timeFormatNamedTimezone},
{time.RubyDate, timeFormatNumericTimezone},
{"2006-01-02 15:04:05Z07:00", timeFormatNumericTimezone},
{"02 Jan 2006", timeFormatNoTimezone},
{"2006-01-02 15:04:05 -07:00", timeFormatNumericTimezone},
{"2006-01-02 15:04:05 -0700", timeFormatNumericTimezone},
{time.Kitchen, timeFormatTimeOnly},
{time.Stamp, timeFormatTimeOnly},
{time.StampMilli, timeFormatTimeOnly},
{time.StampMicro, timeFormatTimeOnly},
{time.StampNano, timeFormatTimeOnly},
}
func parseDateWith(s string, location *time.Location, formats []timeFormat) (d time.Time, e error) {
for _, format := range formats {
if d, e = time.Parse(format.format, s); e == nil {
// Some time formats have a zone name, but no offset, so it gets
// put in that zone name (not the default one passed in to us), but
// without that zone's offset. So set the location manually.
if format.typ <= timeFormatNamedTimezone {
if location == nil {
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | true |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/cast/timeformattype_string.go | vendor/github.com/spf13/cast/timeformattype_string.go | // Code generated by "stringer -type timeFormatType"; DO NOT EDIT.
package cast
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[timeFormatNoTimezone-0]
_ = x[timeFormatNamedTimezone-1]
_ = x[timeFormatNumericTimezone-2]
_ = x[timeFormatNumericAndNamedTimezone-3]
_ = x[timeFormatTimeOnly-4]
}
const _timeFormatType_name = "timeFormatNoTimezonetimeFormatNamedTimezonetimeFormatNumericTimezonetimeFormatNumericAndNamedTimezonetimeFormatTimeOnly"
var _timeFormatType_index = [...]uint8{0, 20, 43, 68, 101, 119}
func (i timeFormatType) String() string {
if i < 0 || i >= timeFormatType(len(_timeFormatType_index)-1) {
return "timeFormatType(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _timeFormatType_name[_timeFormatType_index[i]:_timeFormatType_index[i+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/spf13/cast/cast.go | vendor/github.com/spf13/cast/cast.go | // Copyright © 2014 Steve Francia <spf@spf13.com>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
// Package cast provides easy and safe casting in Go.
package cast
import "time"
// ToBool casts an interface to a bool type.
func ToBool(i interface{}) bool {
v, _ := ToBoolE(i)
return v
}
// ToTime casts an interface to a time.Time type.
func ToTime(i interface{}) time.Time {
v, _ := ToTimeE(i)
return v
}
func ToTimeInDefaultLocation(i interface{}, location *time.Location) time.Time {
v, _ := ToTimeInDefaultLocationE(i, location)
return v
}
// ToDuration casts an interface to a time.Duration type.
func ToDuration(i interface{}) time.Duration {
v, _ := ToDurationE(i)
return v
}
// ToFloat64 casts an interface to a float64 type.
func ToFloat64(i interface{}) float64 {
v, _ := ToFloat64E(i)
return v
}
// ToFloat32 casts an interface to a float32 type.
func ToFloat32(i interface{}) float32 {
v, _ := ToFloat32E(i)
return v
}
// ToInt64 casts an interface to an int64 type.
func ToInt64(i interface{}) int64 {
v, _ := ToInt64E(i)
return v
}
// ToInt32 casts an interface to an int32 type.
func ToInt32(i interface{}) int32 {
v, _ := ToInt32E(i)
return v
}
// ToInt16 casts an interface to an int16 type.
func ToInt16(i interface{}) int16 {
v, _ := ToInt16E(i)
return v
}
// ToInt8 casts an interface to an int8 type.
func ToInt8(i interface{}) int8 {
v, _ := ToInt8E(i)
return v
}
// ToInt casts an interface to an int type.
func ToInt(i interface{}) int {
v, _ := ToIntE(i)
return v
}
// ToUint casts an interface to a uint type.
func ToUint(i interface{}) uint {
v, _ := ToUintE(i)
return v
}
// ToUint64 casts an interface to a uint64 type.
func ToUint64(i interface{}) uint64 {
v, _ := ToUint64E(i)
return v
}
// ToUint32 casts an interface to a uint32 type.
func ToUint32(i interface{}) uint32 {
v, _ := ToUint32E(i)
return v
}
// ToUint16 casts an interface to a uint16 type.
func ToUint16(i interface{}) uint16 {
v, _ := ToUint16E(i)
return v
}
// ToUint8 casts an interface to a uint8 type.
func ToUint8(i interface{}) uint8 {
v, _ := ToUint8E(i)
return v
}
// ToString casts an interface to a string type.
func ToString(i interface{}) string {
v, _ := ToStringE(i)
return v
}
// ToStringMapString casts an interface to a map[string]string type.
func ToStringMapString(i interface{}) map[string]string {
v, _ := ToStringMapStringE(i)
return v
}
// ToStringMapStringSlice casts an interface to a map[string][]string type.
func ToStringMapStringSlice(i interface{}) map[string][]string {
v, _ := ToStringMapStringSliceE(i)
return v
}
// ToStringMapBool casts an interface to a map[string]bool type.
func ToStringMapBool(i interface{}) map[string]bool {
v, _ := ToStringMapBoolE(i)
return v
}
// ToStringMapInt casts an interface to a map[string]int type.
func ToStringMapInt(i interface{}) map[string]int {
v, _ := ToStringMapIntE(i)
return v
}
// ToStringMapInt64 casts an interface to a map[string]int64 type.
func ToStringMapInt64(i interface{}) map[string]int64 {
v, _ := ToStringMapInt64E(i)
return v
}
// ToStringMap casts an interface to a map[string]interface{} type.
func ToStringMap(i interface{}) map[string]interface{} {
v, _ := ToStringMapE(i)
return v
}
// ToSlice casts an interface to a []interface{} type.
func ToSlice(i interface{}) []interface{} {
v, _ := ToSliceE(i)
return v
}
// ToBoolSlice casts an interface to a []bool type.
func ToBoolSlice(i interface{}) []bool {
v, _ := ToBoolSliceE(i)
return v
}
// ToStringSlice casts an interface to a []string type.
func ToStringSlice(i interface{}) []string {
v, _ := ToStringSliceE(i)
return v
}
// ToIntSlice casts an interface to a []int type.
func ToIntSlice(i interface{}) []int {
v, _ := ToIntSliceE(i)
return v
}
// ToDurationSlice casts an interface to a []time.Duration type.
func ToDurationSlice(i interface{}) []time.Duration {
v, _ := ToDurationSliceE(i)
return 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/spf13/pflag/flag.go | vendor/github.com/spf13/pflag/flag.go | // Copyright 2009 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 pflag is a drop-in replacement for Go's flag package, implementing
POSIX/GNU-style --flags.
pflag is compatible with the GNU extensions to the POSIX recommendations
for command-line options. See
http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
Usage:
pflag is a drop-in replacement of Go's native flag package. If you import
pflag under the name "flag" then all code should continue to function
with no changes.
import flag "github.com/spf13/pflag"
There is one exception to this: if you directly instantiate the Flag struct
there is one more field "Shorthand" that you will need to set.
Most code never instantiates this struct directly, and instead uses
functions such as String(), BoolVar(), and Var(), and is therefore
unaffected.
Define flags using flag.String(), Bool(), Int(), etc.
This declares an integer flag, -flagname, stored in the pointer ip, with type *int.
var ip = flag.Int("flagname", 1234, "help message for flagname")
If you like, you can bind the flag to a variable using the Var() functions.
var flagvar int
func init() {
flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
}
Or you can create custom flags that satisfy the Value interface (with
pointer receivers) and couple them to flag parsing by
flag.Var(&flagVal, "name", "help message for flagname")
For such flags, the default value is just the initial value of the variable.
After all flags are defined, call
flag.Parse()
to parse the command line into the defined flags.
Flags may then be used directly. If you're using the flags themselves,
they are all pointers; if you bind to variables, they're values.
fmt.Println("ip has value ", *ip)
fmt.Println("flagvar has value ", flagvar)
After parsing, the arguments after the flag are available as the
slice flag.Args() or individually as flag.Arg(i).
The arguments are indexed from 0 through flag.NArg()-1.
The pflag package also defines some new functions that are not in flag,
that give one-letter shorthands for flags. You can use these by appending
'P' to the name of any function that defines a flag.
var ip = flag.IntP("flagname", "f", 1234, "help message")
var flagvar bool
func init() {
flag.BoolVarP(&flagvar, "boolname", "b", true, "help message")
}
flag.VarP(&flagval, "varname", "v", "help message")
Shorthand letters can be used with single dashes on the command line.
Boolean shorthand flags can be combined with other shorthand flags.
Command line flag syntax:
--flag // boolean flags only
--flag=x
Unlike the flag package, a single dash before an option means something
different than a double dash. Single dashes signify a series of shorthand
letters for flags. All but the last shorthand letter must be boolean flags.
// boolean flags
-f
-abc
// non-boolean flags
-n 1234
-Ifile
// mixed
-abcs "hello"
-abcn1234
Flag parsing stops after the terminator "--". Unlike the flag package,
flags can be interspersed with arguments anywhere on the command line
before this terminator.
Integer flags accept 1234, 0664, 0x1234 and may be negative.
Boolean flags (in their long form) accept 1, 0, t, f, true, false,
TRUE, FALSE, True, False.
Duration flags accept any input valid for time.ParseDuration.
The default set of command-line flags is controlled by
top-level functions. The FlagSet type allows one to define
independent sets of flags, such as to implement subcommands
in a command-line interface. The methods of FlagSet are
analogous to the top-level functions for the command-line
flag set.
*/
package pflag
import (
"bytes"
"errors"
goflag "flag"
"fmt"
"io"
"os"
"sort"
"strings"
)
// ErrHelp is the error returned if the flag -help is invoked but no such flag is defined.
var ErrHelp = errors.New("pflag: help requested")
// ErrorHandling defines how to handle flag parsing errors.
type ErrorHandling int
const (
// ContinueOnError will return an err from Parse() if an error is found
ContinueOnError ErrorHandling = iota
// ExitOnError will call os.Exit(2) if an error is found when parsing
ExitOnError
// PanicOnError will panic() if an error is found when parsing flags
PanicOnError
)
// ParseErrorsWhitelist defines the parsing errors that can be ignored
type ParseErrorsWhitelist struct {
// UnknownFlags will ignore unknown flags errors and continue parsing rest of the flags
UnknownFlags bool
}
// NormalizedName is a flag name that has been normalized according to rules
// for the FlagSet (e.g. making '-' and '_' equivalent).
type NormalizedName string
// A FlagSet represents a set of defined flags.
type FlagSet struct {
// Usage is the function called when an error occurs while parsing flags.
// The field is a function (not a method) that may be changed to point to
// a custom error handler.
Usage func()
// SortFlags is used to indicate, if user wants to have sorted flags in
// help/usage messages.
SortFlags bool
// ParseErrorsWhitelist is used to configure a whitelist of errors
ParseErrorsWhitelist ParseErrorsWhitelist
name string
parsed bool
actual map[NormalizedName]*Flag
orderedActual []*Flag
sortedActual []*Flag
formal map[NormalizedName]*Flag
orderedFormal []*Flag
sortedFormal []*Flag
shorthands map[byte]*Flag
args []string // arguments after flags
argsLenAtDash int // len(args) when a '--' was located when parsing, or -1 if no --
errorHandling ErrorHandling
output io.Writer // nil means stderr; use out() accessor
interspersed bool // allow interspersed option/non-option args
normalizeNameFunc func(f *FlagSet, name string) NormalizedName
addedGoFlagSets []*goflag.FlagSet
}
// A Flag represents the state of a flag.
type Flag struct {
Name string // name as it appears on command line
Shorthand string // one-letter abbreviated flag
Usage string // help message
Value Value // value as set
DefValue string // default value (as text); for usage message
Changed bool // If the user set the value (or if left to default)
NoOptDefVal string // default value (as text); if the flag is on the command line without any options
Deprecated string // If this flag is deprecated, this string is the new or now thing to use
Hidden bool // used by cobra.Command to allow flags to be hidden from help/usage text
ShorthandDeprecated string // If the shorthand of this flag is deprecated, this string is the new or now thing to use
Annotations map[string][]string // used by cobra.Command bash autocomple code
}
// Value is the interface to the dynamic value stored in a flag.
// (The default value is represented as a string.)
type Value interface {
String() string
Set(string) error
Type() string
}
// SliceValue is a secondary interface to all flags which hold a list
// of values. This allows full control over the value of list flags,
// and avoids complicated marshalling and unmarshalling to csv.
type SliceValue interface {
// Append adds the specified value to the end of the flag value list.
Append(string) error
// Replace will fully overwrite any data currently in the flag value list.
Replace([]string) error
// GetSlice returns the flag value list as an array of strings.
GetSlice() []string
}
// sortFlags returns the flags as a slice in lexicographical sorted order.
func sortFlags(flags map[NormalizedName]*Flag) []*Flag {
list := make(sort.StringSlice, len(flags))
i := 0
for k := range flags {
list[i] = string(k)
i++
}
list.Sort()
result := make([]*Flag, len(list))
for i, name := range list {
result[i] = flags[NormalizedName(name)]
}
return result
}
// SetNormalizeFunc allows you to add a function which can translate flag names.
// Flags added to the FlagSet will be translated and then when anything tries to
// look up the flag that will also be translated. So it would be possible to create
// a flag named "getURL" and have it translated to "geturl". A user could then pass
// "--getUrl" which may also be translated to "geturl" and everything will work.
func (f *FlagSet) SetNormalizeFunc(n func(f *FlagSet, name string) NormalizedName) {
f.normalizeNameFunc = n
f.sortedFormal = f.sortedFormal[:0]
for fname, flag := range f.formal {
nname := f.normalizeFlagName(flag.Name)
if fname == nname {
continue
}
flag.Name = string(nname)
delete(f.formal, fname)
f.formal[nname] = flag
if _, set := f.actual[fname]; set {
delete(f.actual, fname)
f.actual[nname] = flag
}
}
}
// GetNormalizeFunc returns the previously set NormalizeFunc of a function which
// does no translation, if not set previously.
func (f *FlagSet) GetNormalizeFunc() func(f *FlagSet, name string) NormalizedName {
if f.normalizeNameFunc != nil {
return f.normalizeNameFunc
}
return func(f *FlagSet, name string) NormalizedName { return NormalizedName(name) }
}
func (f *FlagSet) normalizeFlagName(name string) NormalizedName {
n := f.GetNormalizeFunc()
return n(f, name)
}
func (f *FlagSet) out() io.Writer {
if f.output == nil {
return os.Stderr
}
return f.output
}
// SetOutput sets the destination for usage and error messages.
// If output is nil, os.Stderr is used.
func (f *FlagSet) SetOutput(output io.Writer) {
f.output = output
}
// VisitAll visits the flags in lexicographical order or
// in primordial order if f.SortFlags is false, calling fn for each.
// It visits all flags, even those not set.
func (f *FlagSet) VisitAll(fn func(*Flag)) {
if len(f.formal) == 0 {
return
}
var flags []*Flag
if f.SortFlags {
if len(f.formal) != len(f.sortedFormal) {
f.sortedFormal = sortFlags(f.formal)
}
flags = f.sortedFormal
} else {
flags = f.orderedFormal
}
for _, flag := range flags {
fn(flag)
}
}
// HasFlags returns a bool to indicate if the FlagSet has any flags defined.
func (f *FlagSet) HasFlags() bool {
return len(f.formal) > 0
}
// HasAvailableFlags returns a bool to indicate if the FlagSet has any flags
// that are not hidden.
func (f *FlagSet) HasAvailableFlags() bool {
for _, flag := range f.formal {
if !flag.Hidden {
return true
}
}
return false
}
// VisitAll visits the command-line flags in lexicographical order or
// in primordial order if f.SortFlags is false, calling fn for each.
// It visits all flags, even those not set.
func VisitAll(fn func(*Flag)) {
CommandLine.VisitAll(fn)
}
// Visit visits the flags in lexicographical order or
// in primordial order if f.SortFlags is false, calling fn for each.
// It visits only those flags that have been set.
func (f *FlagSet) Visit(fn func(*Flag)) {
if len(f.actual) == 0 {
return
}
var flags []*Flag
if f.SortFlags {
if len(f.actual) != len(f.sortedActual) {
f.sortedActual = sortFlags(f.actual)
}
flags = f.sortedActual
} else {
flags = f.orderedActual
}
for _, flag := range flags {
fn(flag)
}
}
// Visit visits the command-line flags in lexicographical order or
// in primordial order if f.SortFlags is false, calling fn for each.
// It visits only those flags that have been set.
func Visit(fn func(*Flag)) {
CommandLine.Visit(fn)
}
// Lookup returns the Flag structure of the named flag, returning nil if none exists.
func (f *FlagSet) Lookup(name string) *Flag {
return f.lookup(f.normalizeFlagName(name))
}
// ShorthandLookup returns the Flag structure of the short handed flag,
// returning nil if none exists.
// It panics, if len(name) > 1.
func (f *FlagSet) ShorthandLookup(name string) *Flag {
if name == "" {
return nil
}
if len(name) > 1 {
msg := fmt.Sprintf("can not look up shorthand which is more than one ASCII character: %q", name)
fmt.Fprintf(f.out(), msg)
panic(msg)
}
c := name[0]
return f.shorthands[c]
}
// lookup returns the Flag structure of the named flag, returning nil if none exists.
func (f *FlagSet) lookup(name NormalizedName) *Flag {
return f.formal[name]
}
// func to return a given type for a given flag name
func (f *FlagSet) getFlagType(name string, ftype string, convFunc func(sval string) (interface{}, error)) (interface{}, error) {
flag := f.Lookup(name)
if flag == nil {
err := fmt.Errorf("flag accessed but not defined: %s", name)
return nil, err
}
if flag.Value.Type() != ftype {
err := fmt.Errorf("trying to get %s value of flag of type %s", ftype, flag.Value.Type())
return nil, err
}
sval := flag.Value.String()
result, err := convFunc(sval)
if err != nil {
return nil, err
}
return result, nil
}
// ArgsLenAtDash will return the length of f.Args at the moment when a -- was
// found during arg parsing. This allows your program to know which args were
// before the -- and which came after.
func (f *FlagSet) ArgsLenAtDash() int {
return f.argsLenAtDash
}
// MarkDeprecated indicated that a flag is deprecated in your program. It will
// continue to function but will not show up in help or usage messages. Using
// this flag will also print the given usageMessage.
func (f *FlagSet) MarkDeprecated(name string, usageMessage string) error {
flag := f.Lookup(name)
if flag == nil {
return fmt.Errorf("flag %q does not exist", name)
}
if usageMessage == "" {
return fmt.Errorf("deprecated message for flag %q must be set", name)
}
flag.Deprecated = usageMessage
flag.Hidden = true
return nil
}
// MarkShorthandDeprecated will mark the shorthand of a flag deprecated in your
// program. It will continue to function but will not show up in help or usage
// messages. Using this flag will also print the given usageMessage.
func (f *FlagSet) MarkShorthandDeprecated(name string, usageMessage string) error {
flag := f.Lookup(name)
if flag == nil {
return fmt.Errorf("flag %q does not exist", name)
}
if usageMessage == "" {
return fmt.Errorf("deprecated message for flag %q must be set", name)
}
flag.ShorthandDeprecated = usageMessage
return nil
}
// MarkHidden sets a flag to 'hidden' in your program. It will continue to
// function but will not show up in help or usage messages.
func (f *FlagSet) MarkHidden(name string) error {
flag := f.Lookup(name)
if flag == nil {
return fmt.Errorf("flag %q does not exist", name)
}
flag.Hidden = true
return nil
}
// Lookup returns the Flag structure of the named command-line flag,
// returning nil if none exists.
func Lookup(name string) *Flag {
return CommandLine.Lookup(name)
}
// ShorthandLookup returns the Flag structure of the short handed flag,
// returning nil if none exists.
func ShorthandLookup(name string) *Flag {
return CommandLine.ShorthandLookup(name)
}
// Set sets the value of the named flag.
func (f *FlagSet) Set(name, value string) error {
normalName := f.normalizeFlagName(name)
flag, ok := f.formal[normalName]
if !ok {
return fmt.Errorf("no such flag -%v", name)
}
err := flag.Value.Set(value)
if err != nil {
var flagName string
if flag.Shorthand != "" && flag.ShorthandDeprecated == "" {
flagName = fmt.Sprintf("-%s, --%s", flag.Shorthand, flag.Name)
} else {
flagName = fmt.Sprintf("--%s", flag.Name)
}
return fmt.Errorf("invalid argument %q for %q flag: %v", value, flagName, err)
}
if !flag.Changed {
if f.actual == nil {
f.actual = make(map[NormalizedName]*Flag)
}
f.actual[normalName] = flag
f.orderedActual = append(f.orderedActual, flag)
flag.Changed = true
}
if flag.Deprecated != "" {
fmt.Fprintf(f.out(), "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated)
}
return nil
}
// SetAnnotation allows one to set arbitrary annotations on a flag in the FlagSet.
// This is sometimes used by spf13/cobra programs which want to generate additional
// bash completion information.
func (f *FlagSet) SetAnnotation(name, key string, values []string) error {
normalName := f.normalizeFlagName(name)
flag, ok := f.formal[normalName]
if !ok {
return fmt.Errorf("no such flag -%v", name)
}
if flag.Annotations == nil {
flag.Annotations = map[string][]string{}
}
flag.Annotations[key] = values
return nil
}
// Changed returns true if the flag was explicitly set during Parse() and false
// otherwise
func (f *FlagSet) Changed(name string) bool {
flag := f.Lookup(name)
// If a flag doesn't exist, it wasn't changed....
if flag == nil {
return false
}
return flag.Changed
}
// Set sets the value of the named command-line flag.
func Set(name, value string) error {
return CommandLine.Set(name, value)
}
// PrintDefaults prints, to standard error unless configured
// otherwise, the default values of all defined flags in the set.
func (f *FlagSet) PrintDefaults() {
usages := f.FlagUsages()
fmt.Fprint(f.out(), usages)
}
// defaultIsZeroValue returns true if the default value for this flag represents
// a zero value.
func (f *Flag) defaultIsZeroValue() bool {
switch f.Value.(type) {
case boolFlag:
return f.DefValue == "false"
case *durationValue:
// Beginning in Go 1.7, duration zero values are "0s"
return f.DefValue == "0" || f.DefValue == "0s"
case *intValue, *int8Value, *int32Value, *int64Value, *uintValue, *uint8Value, *uint16Value, *uint32Value, *uint64Value, *countValue, *float32Value, *float64Value:
return f.DefValue == "0"
case *stringValue:
return f.DefValue == ""
case *ipValue, *ipMaskValue, *ipNetValue:
return f.DefValue == "<nil>"
case *intSliceValue, *stringSliceValue, *stringArrayValue:
return f.DefValue == "[]"
default:
switch f.Value.String() {
case "false":
return true
case "<nil>":
return true
case "":
return true
case "0":
return true
}
return false
}
}
// UnquoteUsage extracts a back-quoted name from the usage
// string for a flag and returns it and the un-quoted usage.
// Given "a `name` to show" it returns ("name", "a name to show").
// If there are no back quotes, the name is an educated guess of the
// type of the flag's value, or the empty string if the flag is boolean.
func UnquoteUsage(flag *Flag) (name string, usage string) {
// Look for a back-quoted name, but avoid the strings package.
usage = flag.Usage
for i := 0; i < len(usage); i++ {
if usage[i] == '`' {
for j := i + 1; j < len(usage); j++ {
if usage[j] == '`' {
name = usage[i+1 : j]
usage = usage[:i] + name + usage[j+1:]
return name, usage
}
}
break // Only one back quote; use type name.
}
}
name = flag.Value.Type()
switch name {
case "bool":
name = ""
case "float64":
name = "float"
case "int64":
name = "int"
case "uint64":
name = "uint"
case "stringSlice":
name = "strings"
case "intSlice":
name = "ints"
case "uintSlice":
name = "uints"
case "boolSlice":
name = "bools"
}
return
}
// Splits the string `s` on whitespace into an initial substring up to
// `i` runes in length and the remainder. Will go `slop` over `i` if
// that encompasses the entire string (which allows the caller to
// avoid short orphan words on the final line).
func wrapN(i, slop int, s string) (string, string) {
if i+slop > len(s) {
return s, ""
}
w := strings.LastIndexAny(s[:i], " \t\n")
if w <= 0 {
return s, ""
}
nlPos := strings.LastIndex(s[:i], "\n")
if nlPos > 0 && nlPos < w {
return s[:nlPos], s[nlPos+1:]
}
return s[:w], s[w+1:]
}
// Wraps the string `s` to a maximum width `w` with leading indent
// `i`. The first line is not indented (this is assumed to be done by
// caller). Pass `w` == 0 to do no wrapping
func wrap(i, w int, s string) string {
if w == 0 {
return strings.Replace(s, "\n", "\n"+strings.Repeat(" ", i), -1)
}
// space between indent i and end of line width w into which
// we should wrap the text.
wrap := w - i
var r, l string
// Not enough space for sensible wrapping. Wrap as a block on
// the next line instead.
if wrap < 24 {
i = 16
wrap = w - i
r += "\n" + strings.Repeat(" ", i)
}
// If still not enough space then don't even try to wrap.
if wrap < 24 {
return strings.Replace(s, "\n", r, -1)
}
// Try to avoid short orphan words on the final line, by
// allowing wrapN to go a bit over if that would fit in the
// remainder of the line.
slop := 5
wrap = wrap - slop
// Handle first line, which is indented by the caller (or the
// special case above)
l, s = wrapN(wrap, slop, s)
r = r + strings.Replace(l, "\n", "\n"+strings.Repeat(" ", i), -1)
// Now wrap the rest
for s != "" {
var t string
t, s = wrapN(wrap, slop, s)
r = r + "\n" + strings.Repeat(" ", i) + strings.Replace(t, "\n", "\n"+strings.Repeat(" ", i), -1)
}
return r
}
// FlagUsagesWrapped returns a string containing the usage information
// for all flags in the FlagSet. Wrapped to `cols` columns (0 for no
// wrapping)
func (f *FlagSet) FlagUsagesWrapped(cols int) string {
buf := new(bytes.Buffer)
lines := make([]string, 0, len(f.formal))
maxlen := 0
f.VisitAll(func(flag *Flag) {
if flag.Hidden {
return
}
line := ""
if flag.Shorthand != "" && flag.ShorthandDeprecated == "" {
line = fmt.Sprintf(" -%s, --%s", flag.Shorthand, flag.Name)
} else {
line = fmt.Sprintf(" --%s", flag.Name)
}
varname, usage := UnquoteUsage(flag)
if varname != "" {
line += " " + varname
}
if flag.NoOptDefVal != "" {
switch flag.Value.Type() {
case "string":
line += fmt.Sprintf("[=\"%s\"]", flag.NoOptDefVal)
case "bool":
if flag.NoOptDefVal != "true" {
line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)
}
case "count":
if flag.NoOptDefVal != "+1" {
line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)
}
default:
line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)
}
}
// This special character will be replaced with spacing once the
// correct alignment is calculated
line += "\x00"
if len(line) > maxlen {
maxlen = len(line)
}
line += usage
if !flag.defaultIsZeroValue() {
if flag.Value.Type() == "string" {
line += fmt.Sprintf(" (default %q)", flag.DefValue)
} else {
line += fmt.Sprintf(" (default %s)", flag.DefValue)
}
}
if len(flag.Deprecated) != 0 {
line += fmt.Sprintf(" (DEPRECATED: %s)", flag.Deprecated)
}
lines = append(lines, line)
})
for _, line := range lines {
sidx := strings.Index(line, "\x00")
spacing := strings.Repeat(" ", maxlen-sidx)
// maxlen + 2 comes from + 1 for the \x00 and + 1 for the (deliberate) off-by-one in maxlen-sidx
fmt.Fprintln(buf, line[:sidx], spacing, wrap(maxlen+2, cols, line[sidx+1:]))
}
return buf.String()
}
// FlagUsages returns a string containing the usage information for all flags in
// the FlagSet
func (f *FlagSet) FlagUsages() string {
return f.FlagUsagesWrapped(0)
}
// PrintDefaults prints to standard error the default values of all defined command-line flags.
func PrintDefaults() {
CommandLine.PrintDefaults()
}
// defaultUsage is the default function to print a usage message.
func defaultUsage(f *FlagSet) {
fmt.Fprintf(f.out(), "Usage of %s:\n", f.name)
f.PrintDefaults()
}
// NOTE: Usage is not just defaultUsage(CommandLine)
// because it serves (via godoc flag Usage) as the example
// for how to write your own usage function.
// Usage prints to standard error a usage message documenting all defined command-line flags.
// The function is a variable that may be changed to point to a custom function.
// By default it prints a simple header and calls PrintDefaults; for details about the
// format of the output and how to control it, see the documentation for PrintDefaults.
var Usage = func() {
fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
PrintDefaults()
}
// NFlag returns the number of flags that have been set.
func (f *FlagSet) NFlag() int { return len(f.actual) }
// NFlag returns the number of command-line flags that have been set.
func NFlag() int { return len(CommandLine.actual) }
// Arg returns the i'th argument. Arg(0) is the first remaining argument
// after flags have been processed.
func (f *FlagSet) Arg(i int) string {
if i < 0 || i >= len(f.args) {
return ""
}
return f.args[i]
}
// Arg returns the i'th command-line argument. Arg(0) is the first remaining argument
// after flags have been processed.
func Arg(i int) string {
return CommandLine.Arg(i)
}
// NArg is the number of arguments remaining after flags have been processed.
func (f *FlagSet) NArg() int { return len(f.args) }
// NArg is the number of arguments remaining after flags have been processed.
func NArg() int { return len(CommandLine.args) }
// Args returns the non-flag arguments.
func (f *FlagSet) Args() []string { return f.args }
// Args returns the non-flag command-line arguments.
func Args() []string { return CommandLine.args }
// Var defines a flag with the specified name and usage string. The type and
// value of the flag are represented by the first argument, of type Value, which
// typically holds a user-defined implementation of Value. For instance, the
// caller could create a flag that turns a comma-separated string into a slice
// of strings by giving the slice the methods of Value; in particular, Set would
// decompose the comma-separated string into the slice.
func (f *FlagSet) Var(value Value, name string, usage string) {
f.VarP(value, name, "", usage)
}
// VarPF is like VarP, but returns the flag created
func (f *FlagSet) VarPF(value Value, name, shorthand, usage string) *Flag {
// Remember the default value as a string; it won't change.
flag := &Flag{
Name: name,
Shorthand: shorthand,
Usage: usage,
Value: value,
DefValue: value.String(),
}
f.AddFlag(flag)
return flag
}
// VarP is like Var, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) VarP(value Value, name, shorthand, usage string) {
f.VarPF(value, name, shorthand, usage)
}
// AddFlag will add the flag to the FlagSet
func (f *FlagSet) AddFlag(flag *Flag) {
normalizedFlagName := f.normalizeFlagName(flag.Name)
_, alreadyThere := f.formal[normalizedFlagName]
if alreadyThere {
msg := fmt.Sprintf("%s flag redefined: %s", f.name, flag.Name)
fmt.Fprintln(f.out(), msg)
panic(msg) // Happens only if flags are declared with identical names
}
if f.formal == nil {
f.formal = make(map[NormalizedName]*Flag)
}
flag.Name = string(normalizedFlagName)
f.formal[normalizedFlagName] = flag
f.orderedFormal = append(f.orderedFormal, flag)
if flag.Shorthand == "" {
return
}
if len(flag.Shorthand) > 1 {
msg := fmt.Sprintf("%q shorthand is more than one ASCII character", flag.Shorthand)
fmt.Fprintf(f.out(), msg)
panic(msg)
}
if f.shorthands == nil {
f.shorthands = make(map[byte]*Flag)
}
c := flag.Shorthand[0]
used, alreadyThere := f.shorthands[c]
if alreadyThere {
msg := fmt.Sprintf("unable to redefine %q shorthand in %q flagset: it's already used for %q flag", c, f.name, used.Name)
fmt.Fprintf(f.out(), msg)
panic(msg)
}
f.shorthands[c] = flag
}
// AddFlagSet adds one FlagSet to another. If a flag is already present in f
// the flag from newSet will be ignored.
func (f *FlagSet) AddFlagSet(newSet *FlagSet) {
if newSet == nil {
return
}
newSet.VisitAll(func(flag *Flag) {
if f.Lookup(flag.Name) == nil {
f.AddFlag(flag)
}
})
}
// Var defines a flag with the specified name and usage string. The type and
// value of the flag are represented by the first argument, of type Value, which
// typically holds a user-defined implementation of Value. For instance, the
// caller could create a flag that turns a comma-separated string into a slice
// of strings by giving the slice the methods of Value; in particular, Set would
// decompose the comma-separated string into the slice.
func Var(value Value, name string, usage string) {
CommandLine.VarP(value, name, "", usage)
}
// VarP is like Var, but accepts a shorthand letter that can be used after a single dash.
func VarP(value Value, name, shorthand, usage string) {
CommandLine.VarP(value, name, shorthand, usage)
}
// failf prints to standard error a formatted error and usage message and
// returns the error.
func (f *FlagSet) failf(format string, a ...interface{}) error {
err := fmt.Errorf(format, a...)
if f.errorHandling != ContinueOnError {
fmt.Fprintln(f.out(), err)
f.usage()
}
return err
}
// usage calls the Usage method for the flag set, or the usage function if
// the flag set is CommandLine.
func (f *FlagSet) usage() {
if f == CommandLine {
Usage()
} else if f.Usage == nil {
defaultUsage(f)
} else {
f.Usage()
}
}
//--unknown (args will be empty)
//--unknown --next-flag ... (args will be --next-flag ...)
//--unknown arg ... (args will be arg ...)
func stripUnknownFlagValue(args []string) []string {
if len(args) == 0 {
//--unknown
return args
}
first := args[0]
if len(first) > 0 && first[0] == '-' {
//--unknown --next-flag ...
return args
}
//--unknown arg ... (args will be arg ...)
if len(args) > 1 {
return args[1:]
}
return nil
}
func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []string, err error) {
a = args
name := s[2:]
if len(name) == 0 || name[0] == '-' || name[0] == '=' {
err = f.failf("bad flag syntax: %s", s)
return
}
split := strings.SplitN(name, "=", 2)
name = split[0]
flag, exists := f.formal[f.normalizeFlagName(name)]
if !exists {
switch {
case name == "help":
f.usage()
return a, ErrHelp
case f.ParseErrorsWhitelist.UnknownFlags:
// --unknown=unknownval arg ...
// we do not want to lose arg in this case
if len(split) >= 2 {
return a, nil
}
return stripUnknownFlagValue(a), nil
default:
err = f.failf("unknown flag: --%s", name)
return
}
}
var value string
if len(split) == 2 {
// '--flag=arg'
value = split[1]
} else if flag.NoOptDefVal != "" {
// '--flag' (arg was optional)
value = flag.NoOptDefVal
} else if len(a) > 0 {
// '--flag arg'
value = a[0]
a = a[1:]
} else {
// '--flag' (arg was required)
err = f.failf("flag needs an argument: %s", s)
return
}
err = fn(flag, value)
if err != nil {
f.failf(err.Error())
}
return
}
func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parseFunc) (outShorts string, outArgs []string, err error) {
outArgs = args
if strings.HasPrefix(shorthands, "test.") {
return
}
outShorts = shorthands[1:]
c := shorthands[0]
flag, exists := f.shorthands[c]
if !exists {
switch {
case c == 'h':
f.usage()
err = ErrHelp
return
case f.ParseErrorsWhitelist.UnknownFlags:
// '-f=arg arg ...'
// we do not want to lose arg in this case
if len(shorthands) > 2 && shorthands[1] == '=' {
outShorts = ""
return
}
outArgs = stripUnknownFlagValue(outArgs)
return
default:
err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands)
return
}
}
var value string
if len(shorthands) > 2 && shorthands[1] == '=' {
// '-f=arg'
value = shorthands[2:]
outShorts = ""
} else if flag.NoOptDefVal != "" {
// '-f' (arg was optional)
value = flag.NoOptDefVal
} else if len(shorthands) > 1 {
// '-farg'
value = shorthands[1:]
outShorts = ""
} else if len(args) > 0 {
// '-f arg'
value = args[0]
outArgs = args[1:]
} else {
// '-f' (arg was required)
err = f.failf("flag needs an argument: %q in -%s", c, shorthands)
return
}
if flag.ShorthandDeprecated != "" {
fmt.Fprintf(f.out(), "Flag shorthand -%s has been deprecated, %s\n", flag.Shorthand, flag.ShorthandDeprecated)
}
err = fn(flag, value)
if err != nil {
f.failf(err.Error())
}
return
}
func (f *FlagSet) parseShortArg(s string, args []string, fn parseFunc) (a []string, err error) {
a = args
shorthands := s[1:]
// "shorthands" can be a series of shorthand letters of flags (e.g. "-vvv").
for len(shorthands) > 0 {
shorthands, a, err = f.parseSingleShortArg(shorthands, args, fn)
if err != nil {
return
}
}
return
}
func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) {
for len(args) > 0 {
s := args[0]
args = args[1:]
if len(s) == 0 || s[0] != '-' || len(s) == 1 {
if !f.interspersed {
f.args = append(f.args, s)
f.args = append(f.args, args...)
return nil
}
f.args = append(f.args, s)
continue
}
if s[1] == '-' {
if len(s) == 2 { // "--" terminates the flags
f.argsLenAtDash = len(f.args)
f.args = append(f.args, args...)
break
}
args, err = f.parseLongArg(s, args, fn)
} else {
args, err = f.parseShortArg(s, args, fn)
}
if err != nil {
return
}
}
return
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | true |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/int64.go | vendor/github.com/spf13/pflag/int64.go | package pflag
import "strconv"
// -- int64 Value
type int64Value int64
func newInt64Value(val int64, p *int64) *int64Value {
*p = val
return (*int64Value)(p)
}
func (i *int64Value) Set(s string) error {
v, err := strconv.ParseInt(s, 0, 64)
*i = int64Value(v)
return err
}
func (i *int64Value) Type() string {
return "int64"
}
func (i *int64Value) String() string { return strconv.FormatInt(int64(*i), 10) }
func int64Conv(sval string) (interface{}, error) {
return strconv.ParseInt(sval, 0, 64)
}
// GetInt64 return the int64 value of a flag with the given name
func (f *FlagSet) GetInt64(name string) (int64, error) {
val, err := f.getFlagType(name, "int64", int64Conv)
if err != nil {
return 0, err
}
return val.(int64), nil
}
// Int64Var defines an int64 flag with specified name, default value, and usage string.
// The argument p points to an int64 variable in which to store the value of the flag.
func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string) {
f.VarP(newInt64Value(value, p), name, "", usage)
}
// Int64VarP is like Int64Var, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Int64VarP(p *int64, name, shorthand string, value int64, usage string) {
f.VarP(newInt64Value(value, p), name, shorthand, usage)
}
// Int64Var defines an int64 flag with specified name, default value, and usage string.
// The argument p points to an int64 variable in which to store the value of the flag.
func Int64Var(p *int64, name string, value int64, usage string) {
CommandLine.VarP(newInt64Value(value, p), name, "", usage)
}
// Int64VarP is like Int64Var, but accepts a shorthand letter that can be used after a single dash.
func Int64VarP(p *int64, name, shorthand string, value int64, usage string) {
CommandLine.VarP(newInt64Value(value, p), name, shorthand, usage)
}
// Int64 defines an int64 flag with specified name, default value, and usage string.
// The return value is the address of an int64 variable that stores the value of the flag.
func (f *FlagSet) Int64(name string, value int64, usage string) *int64 {
p := new(int64)
f.Int64VarP(p, name, "", value, usage)
return p
}
// Int64P is like Int64, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Int64P(name, shorthand string, value int64, usage string) *int64 {
p := new(int64)
f.Int64VarP(p, name, shorthand, value, usage)
return p
}
// Int64 defines an int64 flag with specified name, default value, and usage string.
// The return value is the address of an int64 variable that stores the value of the flag.
func Int64(name string, value int64, usage string) *int64 {
return CommandLine.Int64P(name, "", value, usage)
}
// Int64P is like Int64, but accepts a shorthand letter that can be used after a single dash.
func Int64P(name, shorthand string, value int64, usage string) *int64 {
return CommandLine.Int64P(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/uint32.go | vendor/github.com/spf13/pflag/uint32.go | package pflag
import "strconv"
// -- uint32 value
type uint32Value uint32
func newUint32Value(val uint32, p *uint32) *uint32Value {
*p = val
return (*uint32Value)(p)
}
func (i *uint32Value) Set(s string) error {
v, err := strconv.ParseUint(s, 0, 32)
*i = uint32Value(v)
return err
}
func (i *uint32Value) Type() string {
return "uint32"
}
func (i *uint32Value) String() string { return strconv.FormatUint(uint64(*i), 10) }
func uint32Conv(sval string) (interface{}, error) {
v, err := strconv.ParseUint(sval, 0, 32)
if err != nil {
return 0, err
}
return uint32(v), nil
}
// GetUint32 return the uint32 value of a flag with the given name
func (f *FlagSet) GetUint32(name string) (uint32, error) {
val, err := f.getFlagType(name, "uint32", uint32Conv)
if err != nil {
return 0, err
}
return val.(uint32), nil
}
// Uint32Var defines a uint32 flag with specified name, default value, and usage string.
// The argument p points to a uint32 variable in which to store the value of the flag.
func (f *FlagSet) Uint32Var(p *uint32, name string, value uint32, usage string) {
f.VarP(newUint32Value(value, p), name, "", usage)
}
// Uint32VarP is like Uint32Var, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Uint32VarP(p *uint32, name, shorthand string, value uint32, usage string) {
f.VarP(newUint32Value(value, p), name, shorthand, usage)
}
// Uint32Var defines a uint32 flag with specified name, default value, and usage string.
// The argument p points to a uint32 variable in which to store the value of the flag.
func Uint32Var(p *uint32, name string, value uint32, usage string) {
CommandLine.VarP(newUint32Value(value, p), name, "", usage)
}
// Uint32VarP is like Uint32Var, but accepts a shorthand letter that can be used after a single dash.
func Uint32VarP(p *uint32, name, shorthand string, value uint32, usage string) {
CommandLine.VarP(newUint32Value(value, p), name, shorthand, usage)
}
// Uint32 defines a uint32 flag with specified name, default value, and usage string.
// The return value is the address of a uint32 variable that stores the value of the flag.
func (f *FlagSet) Uint32(name string, value uint32, usage string) *uint32 {
p := new(uint32)
f.Uint32VarP(p, name, "", value, usage)
return p
}
// Uint32P is like Uint32, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Uint32P(name, shorthand string, value uint32, usage string) *uint32 {
p := new(uint32)
f.Uint32VarP(p, name, shorthand, value, usage)
return p
}
// Uint32 defines a uint32 flag with specified name, default value, and usage string.
// The return value is the address of a uint32 variable that stores the value of the flag.
func Uint32(name string, value uint32, usage string) *uint32 {
return CommandLine.Uint32P(name, "", value, usage)
}
// Uint32P is like Uint32, but accepts a shorthand letter that can be used after a single dash.
func Uint32P(name, shorthand string, value uint32, usage string) *uint32 {
return CommandLine.Uint32P(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/bool.go | vendor/github.com/spf13/pflag/bool.go | package pflag
import "strconv"
// optional interface to indicate boolean flags that can be
// supplied without "=value" text
type boolFlag interface {
Value
IsBoolFlag() bool
}
// -- bool Value
type boolValue bool
func newBoolValue(val bool, p *bool) *boolValue {
*p = val
return (*boolValue)(p)
}
func (b *boolValue) Set(s string) error {
v, err := strconv.ParseBool(s)
*b = boolValue(v)
return err
}
func (b *boolValue) Type() string {
return "bool"
}
func (b *boolValue) String() string { return strconv.FormatBool(bool(*b)) }
func (b *boolValue) IsBoolFlag() bool { return true }
func boolConv(sval string) (interface{}, error) {
return strconv.ParseBool(sval)
}
// GetBool return the bool value of a flag with the given name
func (f *FlagSet) GetBool(name string) (bool, error) {
val, err := f.getFlagType(name, "bool", boolConv)
if err != nil {
return false, err
}
return val.(bool), nil
}
// BoolVar defines a bool flag with specified name, default value, and usage string.
// The argument p points to a bool variable in which to store the value of the flag.
func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {
f.BoolVarP(p, name, "", value, usage)
}
// BoolVarP is like BoolVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) BoolVarP(p *bool, name, shorthand string, value bool, usage string) {
flag := f.VarPF(newBoolValue(value, p), name, shorthand, usage)
flag.NoOptDefVal = "true"
}
// BoolVar defines a bool flag with specified name, default value, and usage string.
// The argument p points to a bool variable in which to store the value of the flag.
func BoolVar(p *bool, name string, value bool, usage string) {
BoolVarP(p, name, "", value, usage)
}
// BoolVarP is like BoolVar, but accepts a shorthand letter that can be used after a single dash.
func BoolVarP(p *bool, name, shorthand string, value bool, usage string) {
flag := CommandLine.VarPF(newBoolValue(value, p), name, shorthand, usage)
flag.NoOptDefVal = "true"
}
// Bool defines a bool flag with specified name, default value, and usage string.
// The return value is the address of a bool variable that stores the value of the flag.
func (f *FlagSet) Bool(name string, value bool, usage string) *bool {
return f.BoolP(name, "", value, usage)
}
// BoolP is like Bool, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) BoolP(name, shorthand string, value bool, usage string) *bool {
p := new(bool)
f.BoolVarP(p, name, shorthand, value, usage)
return p
}
// Bool defines a bool flag with specified name, default value, and usage string.
// The return value is the address of a bool variable that stores the value of the flag.
func Bool(name string, value bool, usage string) *bool {
return BoolP(name, "", value, usage)
}
// BoolP is like Bool, but accepts a shorthand letter that can be used after a single dash.
func BoolP(name, shorthand string, value bool, usage string) *bool {
b := CommandLine.BoolP(name, shorthand, value, usage)
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/spf13/pflag/string_to_int.go | vendor/github.com/spf13/pflag/string_to_int.go | package pflag
import (
"bytes"
"fmt"
"strconv"
"strings"
)
// -- stringToInt Value
type stringToIntValue struct {
value *map[string]int
changed bool
}
func newStringToIntValue(val map[string]int, p *map[string]int) *stringToIntValue {
ssv := new(stringToIntValue)
ssv.value = p
*ssv.value = val
return ssv
}
// Format: a=1,b=2
func (s *stringToIntValue) Set(val string) error {
ss := strings.Split(val, ",")
out := make(map[string]int, len(ss))
for _, pair := range ss {
kv := strings.SplitN(pair, "=", 2)
if len(kv) != 2 {
return fmt.Errorf("%s must be formatted as key=value", pair)
}
var err error
out[kv[0]], err = strconv.Atoi(kv[1])
if err != nil {
return err
}
}
if !s.changed {
*s.value = out
} else {
for k, v := range out {
(*s.value)[k] = v
}
}
s.changed = true
return nil
}
func (s *stringToIntValue) Type() string {
return "stringToInt"
}
func (s *stringToIntValue) String() string {
var buf bytes.Buffer
i := 0
for k, v := range *s.value {
if i > 0 {
buf.WriteRune(',')
}
buf.WriteString(k)
buf.WriteRune('=')
buf.WriteString(strconv.Itoa(v))
i++
}
return "[" + buf.String() + "]"
}
func stringToIntConv(val string) (interface{}, error) {
val = strings.Trim(val, "[]")
// An empty string would cause an empty map
if len(val) == 0 {
return map[string]int{}, nil
}
ss := strings.Split(val, ",")
out := make(map[string]int, len(ss))
for _, pair := range ss {
kv := strings.SplitN(pair, "=", 2)
if len(kv) != 2 {
return nil, fmt.Errorf("%s must be formatted as key=value", pair)
}
var err error
out[kv[0]], err = strconv.Atoi(kv[1])
if err != nil {
return nil, err
}
}
return out, nil
}
// GetStringToInt return the map[string]int value of a flag with the given name
func (f *FlagSet) GetStringToInt(name string) (map[string]int, error) {
val, err := f.getFlagType(name, "stringToInt", stringToIntConv)
if err != nil {
return map[string]int{}, err
}
return val.(map[string]int), nil
}
// StringToIntVar defines a string flag with specified name, default value, and usage string.
// The argument p points to a map[string]int variable in which to store the values of the multiple flags.
// The value of each argument will not try to be separated by comma
func (f *FlagSet) StringToIntVar(p *map[string]int, name string, value map[string]int, usage string) {
f.VarP(newStringToIntValue(value, p), name, "", usage)
}
// StringToIntVarP is like StringToIntVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) StringToIntVarP(p *map[string]int, name, shorthand string, value map[string]int, usage string) {
f.VarP(newStringToIntValue(value, p), name, shorthand, usage)
}
// StringToIntVar defines a string flag with specified name, default value, and usage string.
// The argument p points to a map[string]int variable in which to store the value of the flag.
// The value of each argument will not try to be separated by comma
func StringToIntVar(p *map[string]int, name string, value map[string]int, usage string) {
CommandLine.VarP(newStringToIntValue(value, p), name, "", usage)
}
// StringToIntVarP is like StringToIntVar, but accepts a shorthand letter that can be used after a single dash.
func StringToIntVarP(p *map[string]int, name, shorthand string, value map[string]int, usage string) {
CommandLine.VarP(newStringToIntValue(value, p), name, shorthand, usage)
}
// StringToInt defines a string flag with specified name, default value, and usage string.
// The return value is the address of a map[string]int variable that stores the value of the flag.
// The value of each argument will not try to be separated by comma
func (f *FlagSet) StringToInt(name string, value map[string]int, usage string) *map[string]int {
p := map[string]int{}
f.StringToIntVarP(&p, name, "", value, usage)
return &p
}
// StringToIntP is like StringToInt, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) StringToIntP(name, shorthand string, value map[string]int, usage string) *map[string]int {
p := map[string]int{}
f.StringToIntVarP(&p, name, shorthand, value, usage)
return &p
}
// StringToInt defines a string flag with specified name, default value, and usage string.
// The return value is the address of a map[string]int variable that stores the value of the flag.
// The value of each argument will not try to be separated by comma
func StringToInt(name string, value map[string]int, usage string) *map[string]int {
return CommandLine.StringToIntP(name, "", value, usage)
}
// StringToIntP is like StringToInt, but accepts a shorthand letter that can be used after a single dash.
func StringToIntP(name, shorthand string, value map[string]int, usage string) *map[string]int {
return CommandLine.StringToIntP(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/duration_slice.go | vendor/github.com/spf13/pflag/duration_slice.go | package pflag
import (
"fmt"
"strings"
"time"
)
// -- durationSlice Value
type durationSliceValue struct {
value *[]time.Duration
changed bool
}
func newDurationSliceValue(val []time.Duration, p *[]time.Duration) *durationSliceValue {
dsv := new(durationSliceValue)
dsv.value = p
*dsv.value = val
return dsv
}
func (s *durationSliceValue) Set(val string) error {
ss := strings.Split(val, ",")
out := make([]time.Duration, len(ss))
for i, d := range ss {
var err error
out[i], err = time.ParseDuration(d)
if err != nil {
return err
}
}
if !s.changed {
*s.value = out
} else {
*s.value = append(*s.value, out...)
}
s.changed = true
return nil
}
func (s *durationSliceValue) Type() string {
return "durationSlice"
}
func (s *durationSliceValue) String() string {
out := make([]string, len(*s.value))
for i, d := range *s.value {
out[i] = fmt.Sprintf("%s", d)
}
return "[" + strings.Join(out, ",") + "]"
}
func (s *durationSliceValue) fromString(val string) (time.Duration, error) {
return time.ParseDuration(val)
}
func (s *durationSliceValue) toString(val time.Duration) string {
return fmt.Sprintf("%s", val)
}
func (s *durationSliceValue) Append(val string) error {
i, err := s.fromString(val)
if err != nil {
return err
}
*s.value = append(*s.value, i)
return nil
}
func (s *durationSliceValue) Replace(val []string) error {
out := make([]time.Duration, len(val))
for i, d := range val {
var err error
out[i], err = s.fromString(d)
if err != nil {
return err
}
}
*s.value = out
return nil
}
func (s *durationSliceValue) GetSlice() []string {
out := make([]string, len(*s.value))
for i, d := range *s.value {
out[i] = s.toString(d)
}
return out
}
func durationSliceConv(val string) (interface{}, error) {
val = strings.Trim(val, "[]")
// Empty string would cause a slice with one (empty) entry
if len(val) == 0 {
return []time.Duration{}, nil
}
ss := strings.Split(val, ",")
out := make([]time.Duration, len(ss))
for i, d := range ss {
var err error
out[i], err = time.ParseDuration(d)
if err != nil {
return nil, err
}
}
return out, nil
}
// GetDurationSlice returns the []time.Duration value of a flag with the given name
func (f *FlagSet) GetDurationSlice(name string) ([]time.Duration, error) {
val, err := f.getFlagType(name, "durationSlice", durationSliceConv)
if err != nil {
return []time.Duration{}, err
}
return val.([]time.Duration), nil
}
// DurationSliceVar defines a durationSlice flag with specified name, default value, and usage string.
// The argument p points to a []time.Duration variable in which to store the value of the flag.
func (f *FlagSet) DurationSliceVar(p *[]time.Duration, name string, value []time.Duration, usage string) {
f.VarP(newDurationSliceValue(value, p), name, "", usage)
}
// DurationSliceVarP is like DurationSliceVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) DurationSliceVarP(p *[]time.Duration, name, shorthand string, value []time.Duration, usage string) {
f.VarP(newDurationSliceValue(value, p), name, shorthand, usage)
}
// DurationSliceVar defines a duration[] flag with specified name, default value, and usage string.
// The argument p points to a duration[] variable in which to store the value of the flag.
func DurationSliceVar(p *[]time.Duration, name string, value []time.Duration, usage string) {
CommandLine.VarP(newDurationSliceValue(value, p), name, "", usage)
}
// DurationSliceVarP is like DurationSliceVar, but accepts a shorthand letter that can be used after a single dash.
func DurationSliceVarP(p *[]time.Duration, name, shorthand string, value []time.Duration, usage string) {
CommandLine.VarP(newDurationSliceValue(value, p), name, shorthand, usage)
}
// DurationSlice defines a []time.Duration flag with specified name, default value, and usage string.
// The return value is the address of a []time.Duration variable that stores the value of the flag.
func (f *FlagSet) DurationSlice(name string, value []time.Duration, usage string) *[]time.Duration {
p := []time.Duration{}
f.DurationSliceVarP(&p, name, "", value, usage)
return &p
}
// DurationSliceP is like DurationSlice, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) DurationSliceP(name, shorthand string, value []time.Duration, usage string) *[]time.Duration {
p := []time.Duration{}
f.DurationSliceVarP(&p, name, shorthand, value, usage)
return &p
}
// DurationSlice defines a []time.Duration flag with specified name, default value, and usage string.
// The return value is the address of a []time.Duration variable that stores the value of the flag.
func DurationSlice(name string, value []time.Duration, usage string) *[]time.Duration {
return CommandLine.DurationSliceP(name, "", value, usage)
}
// DurationSliceP is like DurationSlice, but accepts a shorthand letter that can be used after a single dash.
func DurationSliceP(name, shorthand string, value []time.Duration, usage string) *[]time.Duration {
return CommandLine.DurationSliceP(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/string_slice.go | vendor/github.com/spf13/pflag/string_slice.go | package pflag
import (
"bytes"
"encoding/csv"
"strings"
)
// -- stringSlice Value
type stringSliceValue struct {
value *[]string
changed bool
}
func newStringSliceValue(val []string, p *[]string) *stringSliceValue {
ssv := new(stringSliceValue)
ssv.value = p
*ssv.value = val
return ssv
}
func readAsCSV(val string) ([]string, error) {
if val == "" {
return []string{}, nil
}
stringReader := strings.NewReader(val)
csvReader := csv.NewReader(stringReader)
return csvReader.Read()
}
func writeAsCSV(vals []string) (string, error) {
b := &bytes.Buffer{}
w := csv.NewWriter(b)
err := w.Write(vals)
if err != nil {
return "", err
}
w.Flush()
return strings.TrimSuffix(b.String(), "\n"), nil
}
func (s *stringSliceValue) Set(val string) error {
v, err := readAsCSV(val)
if err != nil {
return err
}
if !s.changed {
*s.value = v
} else {
*s.value = append(*s.value, v...)
}
s.changed = true
return nil
}
func (s *stringSliceValue) Type() string {
return "stringSlice"
}
func (s *stringSliceValue) String() string {
str, _ := writeAsCSV(*s.value)
return "[" + str + "]"
}
func (s *stringSliceValue) Append(val string) error {
*s.value = append(*s.value, val)
return nil
}
func (s *stringSliceValue) Replace(val []string) error {
*s.value = val
return nil
}
func (s *stringSliceValue) GetSlice() []string {
return *s.value
}
func stringSliceConv(sval string) (interface{}, error) {
sval = sval[1 : len(sval)-1]
// An empty string would cause a slice with one (empty) string
if len(sval) == 0 {
return []string{}, nil
}
return readAsCSV(sval)
}
// GetStringSlice return the []string value of a flag with the given name
func (f *FlagSet) GetStringSlice(name string) ([]string, error) {
val, err := f.getFlagType(name, "stringSlice", stringSliceConv)
if err != nil {
return []string{}, err
}
return val.([]string), nil
}
// StringSliceVar defines a string flag with specified name, default value, and usage string.
// The argument p points to a []string variable in which to store the value of the flag.
// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly.
// For example:
// --ss="v1,v2" --ss="v3"
// will result in
// []string{"v1", "v2", "v3"}
func (f *FlagSet) StringSliceVar(p *[]string, name string, value []string, usage string) {
f.VarP(newStringSliceValue(value, p), name, "", usage)
}
// StringSliceVarP is like StringSliceVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) StringSliceVarP(p *[]string, name, shorthand string, value []string, usage string) {
f.VarP(newStringSliceValue(value, p), name, shorthand, usage)
}
// StringSliceVar defines a string flag with specified name, default value, and usage string.
// The argument p points to a []string variable in which to store the value of the flag.
// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly.
// For example:
// --ss="v1,v2" --ss="v3"
// will result in
// []string{"v1", "v2", "v3"}
func StringSliceVar(p *[]string, name string, value []string, usage string) {
CommandLine.VarP(newStringSliceValue(value, p), name, "", usage)
}
// StringSliceVarP is like StringSliceVar, but accepts a shorthand letter that can be used after a single dash.
func StringSliceVarP(p *[]string, name, shorthand string, value []string, usage string) {
CommandLine.VarP(newStringSliceValue(value, p), name, shorthand, usage)
}
// StringSlice defines a string flag with specified name, default value, and usage string.
// The return value is the address of a []string variable that stores the value of the flag.
// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly.
// For example:
// --ss="v1,v2" --ss="v3"
// will result in
// []string{"v1", "v2", "v3"}
func (f *FlagSet) StringSlice(name string, value []string, usage string) *[]string {
p := []string{}
f.StringSliceVarP(&p, name, "", value, usage)
return &p
}
// StringSliceP is like StringSlice, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) StringSliceP(name, shorthand string, value []string, usage string) *[]string {
p := []string{}
f.StringSliceVarP(&p, name, shorthand, value, usage)
return &p
}
// StringSlice defines a string flag with specified name, default value, and usage string.
// The return value is the address of a []string variable that stores the value of the flag.
// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly.
// For example:
// --ss="v1,v2" --ss="v3"
// will result in
// []string{"v1", "v2", "v3"}
func StringSlice(name string, value []string, usage string) *[]string {
return CommandLine.StringSliceP(name, "", value, usage)
}
// StringSliceP is like StringSlice, but accepts a shorthand letter that can be used after a single dash.
func StringSliceP(name, shorthand string, value []string, usage string) *[]string {
return CommandLine.StringSliceP(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/int32_slice.go | vendor/github.com/spf13/pflag/int32_slice.go | package pflag
import (
"fmt"
"strconv"
"strings"
)
// -- int32Slice Value
type int32SliceValue struct {
value *[]int32
changed bool
}
func newInt32SliceValue(val []int32, p *[]int32) *int32SliceValue {
isv := new(int32SliceValue)
isv.value = p
*isv.value = val
return isv
}
func (s *int32SliceValue) Set(val string) error {
ss := strings.Split(val, ",")
out := make([]int32, len(ss))
for i, d := range ss {
var err error
var temp64 int64
temp64, err = strconv.ParseInt(d, 0, 32)
if err != nil {
return err
}
out[i] = int32(temp64)
}
if !s.changed {
*s.value = out
} else {
*s.value = append(*s.value, out...)
}
s.changed = true
return nil
}
func (s *int32SliceValue) Type() string {
return "int32Slice"
}
func (s *int32SliceValue) String() string {
out := make([]string, len(*s.value))
for i, d := range *s.value {
out[i] = fmt.Sprintf("%d", d)
}
return "[" + strings.Join(out, ",") + "]"
}
func (s *int32SliceValue) fromString(val string) (int32, error) {
t64, err := strconv.ParseInt(val, 0, 32)
if err != nil {
return 0, err
}
return int32(t64), nil
}
func (s *int32SliceValue) toString(val int32) string {
return fmt.Sprintf("%d", val)
}
func (s *int32SliceValue) Append(val string) error {
i, err := s.fromString(val)
if err != nil {
return err
}
*s.value = append(*s.value, i)
return nil
}
func (s *int32SliceValue) Replace(val []string) error {
out := make([]int32, len(val))
for i, d := range val {
var err error
out[i], err = s.fromString(d)
if err != nil {
return err
}
}
*s.value = out
return nil
}
func (s *int32SliceValue) GetSlice() []string {
out := make([]string, len(*s.value))
for i, d := range *s.value {
out[i] = s.toString(d)
}
return out
}
func int32SliceConv(val string) (interface{}, error) {
val = strings.Trim(val, "[]")
// Empty string would cause a slice with one (empty) entry
if len(val) == 0 {
return []int32{}, nil
}
ss := strings.Split(val, ",")
out := make([]int32, len(ss))
for i, d := range ss {
var err error
var temp64 int64
temp64, err = strconv.ParseInt(d, 0, 32)
if err != nil {
return nil, err
}
out[i] = int32(temp64)
}
return out, nil
}
// GetInt32Slice return the []int32 value of a flag with the given name
func (f *FlagSet) GetInt32Slice(name string) ([]int32, error) {
val, err := f.getFlagType(name, "int32Slice", int32SliceConv)
if err != nil {
return []int32{}, err
}
return val.([]int32), nil
}
// Int32SliceVar defines a int32Slice flag with specified name, default value, and usage string.
// The argument p points to a []int32 variable in which to store the value of the flag.
func (f *FlagSet) Int32SliceVar(p *[]int32, name string, value []int32, usage string) {
f.VarP(newInt32SliceValue(value, p), name, "", usage)
}
// Int32SliceVarP is like Int32SliceVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Int32SliceVarP(p *[]int32, name, shorthand string, value []int32, usage string) {
f.VarP(newInt32SliceValue(value, p), name, shorthand, usage)
}
// Int32SliceVar defines a int32[] flag with specified name, default value, and usage string.
// The argument p points to a int32[] variable in which to store the value of the flag.
func Int32SliceVar(p *[]int32, name string, value []int32, usage string) {
CommandLine.VarP(newInt32SliceValue(value, p), name, "", usage)
}
// Int32SliceVarP is like Int32SliceVar, but accepts a shorthand letter that can be used after a single dash.
func Int32SliceVarP(p *[]int32, name, shorthand string, value []int32, usage string) {
CommandLine.VarP(newInt32SliceValue(value, p), name, shorthand, usage)
}
// Int32Slice defines a []int32 flag with specified name, default value, and usage string.
// The return value is the address of a []int32 variable that stores the value of the flag.
func (f *FlagSet) Int32Slice(name string, value []int32, usage string) *[]int32 {
p := []int32{}
f.Int32SliceVarP(&p, name, "", value, usage)
return &p
}
// Int32SliceP is like Int32Slice, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Int32SliceP(name, shorthand string, value []int32, usage string) *[]int32 {
p := []int32{}
f.Int32SliceVarP(&p, name, shorthand, value, usage)
return &p
}
// Int32Slice defines a []int32 flag with specified name, default value, and usage string.
// The return value is the address of a []int32 variable that stores the value of the flag.
func Int32Slice(name string, value []int32, usage string) *[]int32 {
return CommandLine.Int32SliceP(name, "", value, usage)
}
// Int32SliceP is like Int32Slice, but accepts a shorthand letter that can be used after a single dash.
func Int32SliceP(name, shorthand string, value []int32, usage string) *[]int32 {
return CommandLine.Int32SliceP(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/uint16.go | vendor/github.com/spf13/pflag/uint16.go | package pflag
import "strconv"
// -- uint16 value
type uint16Value uint16
func newUint16Value(val uint16, p *uint16) *uint16Value {
*p = val
return (*uint16Value)(p)
}
func (i *uint16Value) Set(s string) error {
v, err := strconv.ParseUint(s, 0, 16)
*i = uint16Value(v)
return err
}
func (i *uint16Value) Type() string {
return "uint16"
}
func (i *uint16Value) String() string { return strconv.FormatUint(uint64(*i), 10) }
func uint16Conv(sval string) (interface{}, error) {
v, err := strconv.ParseUint(sval, 0, 16)
if err != nil {
return 0, err
}
return uint16(v), nil
}
// GetUint16 return the uint16 value of a flag with the given name
func (f *FlagSet) GetUint16(name string) (uint16, error) {
val, err := f.getFlagType(name, "uint16", uint16Conv)
if err != nil {
return 0, err
}
return val.(uint16), nil
}
// Uint16Var defines a uint flag with specified name, default value, and usage string.
// The argument p points to a uint variable in which to store the value of the flag.
func (f *FlagSet) Uint16Var(p *uint16, name string, value uint16, usage string) {
f.VarP(newUint16Value(value, p), name, "", usage)
}
// Uint16VarP is like Uint16Var, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Uint16VarP(p *uint16, name, shorthand string, value uint16, usage string) {
f.VarP(newUint16Value(value, p), name, shorthand, usage)
}
// Uint16Var defines a uint flag with specified name, default value, and usage string.
// The argument p points to a uint variable in which to store the value of the flag.
func Uint16Var(p *uint16, name string, value uint16, usage string) {
CommandLine.VarP(newUint16Value(value, p), name, "", usage)
}
// Uint16VarP is like Uint16Var, but accepts a shorthand letter that can be used after a single dash.
func Uint16VarP(p *uint16, name, shorthand string, value uint16, usage string) {
CommandLine.VarP(newUint16Value(value, p), name, shorthand, usage)
}
// Uint16 defines a uint flag with specified name, default value, and usage string.
// The return value is the address of a uint variable that stores the value of the flag.
func (f *FlagSet) Uint16(name string, value uint16, usage string) *uint16 {
p := new(uint16)
f.Uint16VarP(p, name, "", value, usage)
return p
}
// Uint16P is like Uint16, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Uint16P(name, shorthand string, value uint16, usage string) *uint16 {
p := new(uint16)
f.Uint16VarP(p, name, shorthand, value, usage)
return p
}
// Uint16 defines a uint flag with specified name, default value, and usage string.
// The return value is the address of a uint variable that stores the value of the flag.
func Uint16(name string, value uint16, usage string) *uint16 {
return CommandLine.Uint16P(name, "", value, usage)
}
// Uint16P is like Uint16, but accepts a shorthand letter that can be used after a single dash.
func Uint16P(name, shorthand string, value uint16, usage string) *uint16 {
return CommandLine.Uint16P(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/ipmask.go | vendor/github.com/spf13/pflag/ipmask.go | package pflag
import (
"fmt"
"net"
"strconv"
)
// -- net.IPMask value
type ipMaskValue net.IPMask
func newIPMaskValue(val net.IPMask, p *net.IPMask) *ipMaskValue {
*p = val
return (*ipMaskValue)(p)
}
func (i *ipMaskValue) String() string { return net.IPMask(*i).String() }
func (i *ipMaskValue) Set(s string) error {
ip := ParseIPv4Mask(s)
if ip == nil {
return fmt.Errorf("failed to parse IP mask: %q", s)
}
*i = ipMaskValue(ip)
return nil
}
func (i *ipMaskValue) Type() string {
return "ipMask"
}
// ParseIPv4Mask written in IP form (e.g. 255.255.255.0).
// This function should really belong to the net package.
func ParseIPv4Mask(s string) net.IPMask {
mask := net.ParseIP(s)
if mask == nil {
if len(s) != 8 {
return nil
}
// net.IPMask.String() actually outputs things like ffffff00
// so write a horrible parser for that as well :-(
m := []int{}
for i := 0; i < 4; i++ {
b := "0x" + s[2*i:2*i+2]
d, err := strconv.ParseInt(b, 0, 0)
if err != nil {
return nil
}
m = append(m, int(d))
}
s := fmt.Sprintf("%d.%d.%d.%d", m[0], m[1], m[2], m[3])
mask = net.ParseIP(s)
if mask == nil {
return nil
}
}
return net.IPv4Mask(mask[12], mask[13], mask[14], mask[15])
}
func parseIPv4Mask(sval string) (interface{}, error) {
mask := ParseIPv4Mask(sval)
if mask == nil {
return nil, fmt.Errorf("unable to parse %s as net.IPMask", sval)
}
return mask, nil
}
// GetIPv4Mask return the net.IPv4Mask value of a flag with the given name
func (f *FlagSet) GetIPv4Mask(name string) (net.IPMask, error) {
val, err := f.getFlagType(name, "ipMask", parseIPv4Mask)
if err != nil {
return nil, err
}
return val.(net.IPMask), nil
}
// IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string.
// The argument p points to an net.IPMask variable in which to store the value of the flag.
func (f *FlagSet) IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) {
f.VarP(newIPMaskValue(value, p), name, "", usage)
}
// IPMaskVarP is like IPMaskVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) {
f.VarP(newIPMaskValue(value, p), name, shorthand, usage)
}
// IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string.
// The argument p points to an net.IPMask variable in which to store the value of the flag.
func IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) {
CommandLine.VarP(newIPMaskValue(value, p), name, "", usage)
}
// IPMaskVarP is like IPMaskVar, but accepts a shorthand letter that can be used after a single dash.
func IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) {
CommandLine.VarP(newIPMaskValue(value, p), name, shorthand, usage)
}
// IPMask defines an net.IPMask flag with specified name, default value, and usage string.
// The return value is the address of an net.IPMask variable that stores the value of the flag.
func (f *FlagSet) IPMask(name string, value net.IPMask, usage string) *net.IPMask {
p := new(net.IPMask)
f.IPMaskVarP(p, name, "", value, usage)
return p
}
// IPMaskP is like IPMask, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask {
p := new(net.IPMask)
f.IPMaskVarP(p, name, shorthand, value, usage)
return p
}
// IPMask defines an net.IPMask flag with specified name, default value, and usage string.
// The return value is the address of an net.IPMask variable that stores the value of the flag.
func IPMask(name string, value net.IPMask, usage string) *net.IPMask {
return CommandLine.IPMaskP(name, "", value, usage)
}
// IPMaskP is like IP, but accepts a shorthand letter that can be used after a single dash.
func IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask {
return CommandLine.IPMaskP(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/int_slice.go | vendor/github.com/spf13/pflag/int_slice.go | package pflag
import (
"fmt"
"strconv"
"strings"
)
// -- intSlice Value
type intSliceValue struct {
value *[]int
changed bool
}
func newIntSliceValue(val []int, p *[]int) *intSliceValue {
isv := new(intSliceValue)
isv.value = p
*isv.value = val
return isv
}
func (s *intSliceValue) Set(val string) error {
ss := strings.Split(val, ",")
out := make([]int, len(ss))
for i, d := range ss {
var err error
out[i], err = strconv.Atoi(d)
if err != nil {
return err
}
}
if !s.changed {
*s.value = out
} else {
*s.value = append(*s.value, out...)
}
s.changed = true
return nil
}
func (s *intSliceValue) Type() string {
return "intSlice"
}
func (s *intSliceValue) String() string {
out := make([]string, len(*s.value))
for i, d := range *s.value {
out[i] = fmt.Sprintf("%d", d)
}
return "[" + strings.Join(out, ",") + "]"
}
func (s *intSliceValue) Append(val string) error {
i, err := strconv.Atoi(val)
if err != nil {
return err
}
*s.value = append(*s.value, i)
return nil
}
func (s *intSliceValue) Replace(val []string) error {
out := make([]int, len(val))
for i, d := range val {
var err error
out[i], err = strconv.Atoi(d)
if err != nil {
return err
}
}
*s.value = out
return nil
}
func (s *intSliceValue) GetSlice() []string {
out := make([]string, len(*s.value))
for i, d := range *s.value {
out[i] = strconv.Itoa(d)
}
return out
}
func intSliceConv(val string) (interface{}, error) {
val = strings.Trim(val, "[]")
// Empty string would cause a slice with one (empty) entry
if len(val) == 0 {
return []int{}, nil
}
ss := strings.Split(val, ",")
out := make([]int, len(ss))
for i, d := range ss {
var err error
out[i], err = strconv.Atoi(d)
if err != nil {
return nil, err
}
}
return out, nil
}
// GetIntSlice return the []int value of a flag with the given name
func (f *FlagSet) GetIntSlice(name string) ([]int, error) {
val, err := f.getFlagType(name, "intSlice", intSliceConv)
if err != nil {
return []int{}, err
}
return val.([]int), nil
}
// IntSliceVar defines a intSlice flag with specified name, default value, and usage string.
// The argument p points to a []int variable in which to store the value of the flag.
func (f *FlagSet) IntSliceVar(p *[]int, name string, value []int, usage string) {
f.VarP(newIntSliceValue(value, p), name, "", usage)
}
// IntSliceVarP is like IntSliceVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) IntSliceVarP(p *[]int, name, shorthand string, value []int, usage string) {
f.VarP(newIntSliceValue(value, p), name, shorthand, usage)
}
// IntSliceVar defines a int[] flag with specified name, default value, and usage string.
// The argument p points to a int[] variable in which to store the value of the flag.
func IntSliceVar(p *[]int, name string, value []int, usage string) {
CommandLine.VarP(newIntSliceValue(value, p), name, "", usage)
}
// IntSliceVarP is like IntSliceVar, but accepts a shorthand letter that can be used after a single dash.
func IntSliceVarP(p *[]int, name, shorthand string, value []int, usage string) {
CommandLine.VarP(newIntSliceValue(value, p), name, shorthand, usage)
}
// IntSlice defines a []int flag with specified name, default value, and usage string.
// The return value is the address of a []int variable that stores the value of the flag.
func (f *FlagSet) IntSlice(name string, value []int, usage string) *[]int {
p := []int{}
f.IntSliceVarP(&p, name, "", value, usage)
return &p
}
// IntSliceP is like IntSlice, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) IntSliceP(name, shorthand string, value []int, usage string) *[]int {
p := []int{}
f.IntSliceVarP(&p, name, shorthand, value, usage)
return &p
}
// IntSlice defines a []int flag with specified name, default value, and usage string.
// The return value is the address of a []int variable that stores the value of the flag.
func IntSlice(name string, value []int, usage string) *[]int {
return CommandLine.IntSliceP(name, "", value, usage)
}
// IntSliceP is like IntSlice, but accepts a shorthand letter that can be used after a single dash.
func IntSliceP(name, shorthand string, value []int, usage string) *[]int {
return CommandLine.IntSliceP(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/int16.go | vendor/github.com/spf13/pflag/int16.go | package pflag
import "strconv"
// -- int16 Value
type int16Value int16
func newInt16Value(val int16, p *int16) *int16Value {
*p = val
return (*int16Value)(p)
}
func (i *int16Value) Set(s string) error {
v, err := strconv.ParseInt(s, 0, 16)
*i = int16Value(v)
return err
}
func (i *int16Value) Type() string {
return "int16"
}
func (i *int16Value) String() string { return strconv.FormatInt(int64(*i), 10) }
func int16Conv(sval string) (interface{}, error) {
v, err := strconv.ParseInt(sval, 0, 16)
if err != nil {
return 0, err
}
return int16(v), nil
}
// GetInt16 returns the int16 value of a flag with the given name
func (f *FlagSet) GetInt16(name string) (int16, error) {
val, err := f.getFlagType(name, "int16", int16Conv)
if err != nil {
return 0, err
}
return val.(int16), nil
}
// Int16Var defines an int16 flag with specified name, default value, and usage string.
// The argument p points to an int16 variable in which to store the value of the flag.
func (f *FlagSet) Int16Var(p *int16, name string, value int16, usage string) {
f.VarP(newInt16Value(value, p), name, "", usage)
}
// Int16VarP is like Int16Var, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Int16VarP(p *int16, name, shorthand string, value int16, usage string) {
f.VarP(newInt16Value(value, p), name, shorthand, usage)
}
// Int16Var defines an int16 flag with specified name, default value, and usage string.
// The argument p points to an int16 variable in which to store the value of the flag.
func Int16Var(p *int16, name string, value int16, usage string) {
CommandLine.VarP(newInt16Value(value, p), name, "", usage)
}
// Int16VarP is like Int16Var, but accepts a shorthand letter that can be used after a single dash.
func Int16VarP(p *int16, name, shorthand string, value int16, usage string) {
CommandLine.VarP(newInt16Value(value, p), name, shorthand, usage)
}
// Int16 defines an int16 flag with specified name, default value, and usage string.
// The return value is the address of an int16 variable that stores the value of the flag.
func (f *FlagSet) Int16(name string, value int16, usage string) *int16 {
p := new(int16)
f.Int16VarP(p, name, "", value, usage)
return p
}
// Int16P is like Int16, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Int16P(name, shorthand string, value int16, usage string) *int16 {
p := new(int16)
f.Int16VarP(p, name, shorthand, value, usage)
return p
}
// Int16 defines an int16 flag with specified name, default value, and usage string.
// The return value is the address of an int16 variable that stores the value of the flag.
func Int16(name string, value int16, usage string) *int16 {
return CommandLine.Int16P(name, "", value, usage)
}
// Int16P is like Int16, but accepts a shorthand letter that can be used after a single dash.
func Int16P(name, shorthand string, value int16, usage string) *int16 {
return CommandLine.Int16P(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/float32.go | vendor/github.com/spf13/pflag/float32.go | package pflag
import "strconv"
// -- float32 Value
type float32Value float32
func newFloat32Value(val float32, p *float32) *float32Value {
*p = val
return (*float32Value)(p)
}
func (f *float32Value) Set(s string) error {
v, err := strconv.ParseFloat(s, 32)
*f = float32Value(v)
return err
}
func (f *float32Value) Type() string {
return "float32"
}
func (f *float32Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 32) }
func float32Conv(sval string) (interface{}, error) {
v, err := strconv.ParseFloat(sval, 32)
if err != nil {
return 0, err
}
return float32(v), nil
}
// GetFloat32 return the float32 value of a flag with the given name
func (f *FlagSet) GetFloat32(name string) (float32, error) {
val, err := f.getFlagType(name, "float32", float32Conv)
if err != nil {
return 0, err
}
return val.(float32), nil
}
// Float32Var defines a float32 flag with specified name, default value, and usage string.
// The argument p points to a float32 variable in which to store the value of the flag.
func (f *FlagSet) Float32Var(p *float32, name string, value float32, usage string) {
f.VarP(newFloat32Value(value, p), name, "", usage)
}
// Float32VarP is like Float32Var, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Float32VarP(p *float32, name, shorthand string, value float32, usage string) {
f.VarP(newFloat32Value(value, p), name, shorthand, usage)
}
// Float32Var defines a float32 flag with specified name, default value, and usage string.
// The argument p points to a float32 variable in which to store the value of the flag.
func Float32Var(p *float32, name string, value float32, usage string) {
CommandLine.VarP(newFloat32Value(value, p), name, "", usage)
}
// Float32VarP is like Float32Var, but accepts a shorthand letter that can be used after a single dash.
func Float32VarP(p *float32, name, shorthand string, value float32, usage string) {
CommandLine.VarP(newFloat32Value(value, p), name, shorthand, usage)
}
// Float32 defines a float32 flag with specified name, default value, and usage string.
// The return value is the address of a float32 variable that stores the value of the flag.
func (f *FlagSet) Float32(name string, value float32, usage string) *float32 {
p := new(float32)
f.Float32VarP(p, name, "", value, usage)
return p
}
// Float32P is like Float32, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Float32P(name, shorthand string, value float32, usage string) *float32 {
p := new(float32)
f.Float32VarP(p, name, shorthand, value, usage)
return p
}
// Float32 defines a float32 flag with specified name, default value, and usage string.
// The return value is the address of a float32 variable that stores the value of the flag.
func Float32(name string, value float32, usage string) *float32 {
return CommandLine.Float32P(name, "", value, usage)
}
// Float32P is like Float32, but accepts a shorthand letter that can be used after a single dash.
func Float32P(name, shorthand string, value float32, usage string) *float32 {
return CommandLine.Float32P(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/int8.go | vendor/github.com/spf13/pflag/int8.go | package pflag
import "strconv"
// -- int8 Value
type int8Value int8
func newInt8Value(val int8, p *int8) *int8Value {
*p = val
return (*int8Value)(p)
}
func (i *int8Value) Set(s string) error {
v, err := strconv.ParseInt(s, 0, 8)
*i = int8Value(v)
return err
}
func (i *int8Value) Type() string {
return "int8"
}
func (i *int8Value) String() string { return strconv.FormatInt(int64(*i), 10) }
func int8Conv(sval string) (interface{}, error) {
v, err := strconv.ParseInt(sval, 0, 8)
if err != nil {
return 0, err
}
return int8(v), nil
}
// GetInt8 return the int8 value of a flag with the given name
func (f *FlagSet) GetInt8(name string) (int8, error) {
val, err := f.getFlagType(name, "int8", int8Conv)
if err != nil {
return 0, err
}
return val.(int8), nil
}
// Int8Var defines an int8 flag with specified name, default value, and usage string.
// The argument p points to an int8 variable in which to store the value of the flag.
func (f *FlagSet) Int8Var(p *int8, name string, value int8, usage string) {
f.VarP(newInt8Value(value, p), name, "", usage)
}
// Int8VarP is like Int8Var, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Int8VarP(p *int8, name, shorthand string, value int8, usage string) {
f.VarP(newInt8Value(value, p), name, shorthand, usage)
}
// Int8Var defines an int8 flag with specified name, default value, and usage string.
// The argument p points to an int8 variable in which to store the value of the flag.
func Int8Var(p *int8, name string, value int8, usage string) {
CommandLine.VarP(newInt8Value(value, p), name, "", usage)
}
// Int8VarP is like Int8Var, but accepts a shorthand letter that can be used after a single dash.
func Int8VarP(p *int8, name, shorthand string, value int8, usage string) {
CommandLine.VarP(newInt8Value(value, p), name, shorthand, usage)
}
// Int8 defines an int8 flag with specified name, default value, and usage string.
// The return value is the address of an int8 variable that stores the value of the flag.
func (f *FlagSet) Int8(name string, value int8, usage string) *int8 {
p := new(int8)
f.Int8VarP(p, name, "", value, usage)
return p
}
// Int8P is like Int8, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Int8P(name, shorthand string, value int8, usage string) *int8 {
p := new(int8)
f.Int8VarP(p, name, shorthand, value, usage)
return p
}
// Int8 defines an int8 flag with specified name, default value, and usage string.
// The return value is the address of an int8 variable that stores the value of the flag.
func Int8(name string, value int8, usage string) *int8 {
return CommandLine.Int8P(name, "", value, usage)
}
// Int8P is like Int8, but accepts a shorthand letter that can be used after a single dash.
func Int8P(name, shorthand string, value int8, usage string) *int8 {
return CommandLine.Int8P(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/uint.go | vendor/github.com/spf13/pflag/uint.go | package pflag
import "strconv"
// -- uint Value
type uintValue uint
func newUintValue(val uint, p *uint) *uintValue {
*p = val
return (*uintValue)(p)
}
func (i *uintValue) Set(s string) error {
v, err := strconv.ParseUint(s, 0, 64)
*i = uintValue(v)
return err
}
func (i *uintValue) Type() string {
return "uint"
}
func (i *uintValue) String() string { return strconv.FormatUint(uint64(*i), 10) }
func uintConv(sval string) (interface{}, error) {
v, err := strconv.ParseUint(sval, 0, 0)
if err != nil {
return 0, err
}
return uint(v), nil
}
// GetUint return the uint value of a flag with the given name
func (f *FlagSet) GetUint(name string) (uint, error) {
val, err := f.getFlagType(name, "uint", uintConv)
if err != nil {
return 0, err
}
return val.(uint), nil
}
// UintVar defines a uint flag with specified name, default value, and usage string.
// The argument p points to a uint variable in which to store the value of the flag.
func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string) {
f.VarP(newUintValue(value, p), name, "", usage)
}
// UintVarP is like UintVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) UintVarP(p *uint, name, shorthand string, value uint, usage string) {
f.VarP(newUintValue(value, p), name, shorthand, usage)
}
// UintVar defines a uint flag with specified name, default value, and usage string.
// The argument p points to a uint variable in which to store the value of the flag.
func UintVar(p *uint, name string, value uint, usage string) {
CommandLine.VarP(newUintValue(value, p), name, "", usage)
}
// UintVarP is like UintVar, but accepts a shorthand letter that can be used after a single dash.
func UintVarP(p *uint, name, shorthand string, value uint, usage string) {
CommandLine.VarP(newUintValue(value, p), name, shorthand, usage)
}
// Uint defines a uint flag with specified name, default value, and usage string.
// The return value is the address of a uint variable that stores the value of the flag.
func (f *FlagSet) Uint(name string, value uint, usage string) *uint {
p := new(uint)
f.UintVarP(p, name, "", value, usage)
return p
}
// UintP is like Uint, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) UintP(name, shorthand string, value uint, usage string) *uint {
p := new(uint)
f.UintVarP(p, name, shorthand, value, usage)
return p
}
// Uint defines a uint flag with specified name, default value, and usage string.
// The return value is the address of a uint variable that stores the value of the flag.
func Uint(name string, value uint, usage string) *uint {
return CommandLine.UintP(name, "", value, usage)
}
// UintP is like Uint, but accepts a shorthand letter that can be used after a single dash.
func UintP(name, shorthand string, value uint, usage string) *uint {
return CommandLine.UintP(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/ipnet.go | vendor/github.com/spf13/pflag/ipnet.go | package pflag
import (
"fmt"
"net"
"strings"
)
// IPNet adapts net.IPNet for use as a flag.
type ipNetValue net.IPNet
func (ipnet ipNetValue) String() string {
n := net.IPNet(ipnet)
return n.String()
}
func (ipnet *ipNetValue) Set(value string) error {
_, n, err := net.ParseCIDR(strings.TrimSpace(value))
if err != nil {
return err
}
*ipnet = ipNetValue(*n)
return nil
}
func (*ipNetValue) Type() string {
return "ipNet"
}
func newIPNetValue(val net.IPNet, p *net.IPNet) *ipNetValue {
*p = val
return (*ipNetValue)(p)
}
func ipNetConv(sval string) (interface{}, error) {
_, n, err := net.ParseCIDR(strings.TrimSpace(sval))
if err == nil {
return *n, nil
}
return nil, fmt.Errorf("invalid string being converted to IPNet: %s", sval)
}
// GetIPNet return the net.IPNet value of a flag with the given name
func (f *FlagSet) GetIPNet(name string) (net.IPNet, error) {
val, err := f.getFlagType(name, "ipNet", ipNetConv)
if err != nil {
return net.IPNet{}, err
}
return val.(net.IPNet), nil
}
// IPNetVar defines an net.IPNet flag with specified name, default value, and usage string.
// The argument p points to an net.IPNet variable in which to store the value of the flag.
func (f *FlagSet) IPNetVar(p *net.IPNet, name string, value net.IPNet, usage string) {
f.VarP(newIPNetValue(value, p), name, "", usage)
}
// IPNetVarP is like IPNetVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) IPNetVarP(p *net.IPNet, name, shorthand string, value net.IPNet, usage string) {
f.VarP(newIPNetValue(value, p), name, shorthand, usage)
}
// IPNetVar defines an net.IPNet flag with specified name, default value, and usage string.
// The argument p points to an net.IPNet variable in which to store the value of the flag.
func IPNetVar(p *net.IPNet, name string, value net.IPNet, usage string) {
CommandLine.VarP(newIPNetValue(value, p), name, "", usage)
}
// IPNetVarP is like IPNetVar, but accepts a shorthand letter that can be used after a single dash.
func IPNetVarP(p *net.IPNet, name, shorthand string, value net.IPNet, usage string) {
CommandLine.VarP(newIPNetValue(value, p), name, shorthand, usage)
}
// IPNet defines an net.IPNet flag with specified name, default value, and usage string.
// The return value is the address of an net.IPNet variable that stores the value of the flag.
func (f *FlagSet) IPNet(name string, value net.IPNet, usage string) *net.IPNet {
p := new(net.IPNet)
f.IPNetVarP(p, name, "", value, usage)
return p
}
// IPNetP is like IPNet, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) IPNetP(name, shorthand string, value net.IPNet, usage string) *net.IPNet {
p := new(net.IPNet)
f.IPNetVarP(p, name, shorthand, value, usage)
return p
}
// IPNet defines an net.IPNet flag with specified name, default value, and usage string.
// The return value is the address of an net.IPNet variable that stores the value of the flag.
func IPNet(name string, value net.IPNet, usage string) *net.IPNet {
return CommandLine.IPNetP(name, "", value, usage)
}
// IPNetP is like IPNet, but accepts a shorthand letter that can be used after a single dash.
func IPNetP(name, shorthand string, value net.IPNet, usage string) *net.IPNet {
return CommandLine.IPNetP(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/ip_slice.go | vendor/github.com/spf13/pflag/ip_slice.go | package pflag
import (
"fmt"
"io"
"net"
"strings"
)
// -- ipSlice Value
type ipSliceValue struct {
value *[]net.IP
changed bool
}
func newIPSliceValue(val []net.IP, p *[]net.IP) *ipSliceValue {
ipsv := new(ipSliceValue)
ipsv.value = p
*ipsv.value = val
return ipsv
}
// Set converts, and assigns, the comma-separated IP argument string representation as the []net.IP value of this flag.
// If Set is called on a flag that already has a []net.IP assigned, the newly converted values will be appended.
func (s *ipSliceValue) Set(val string) error {
// remove all quote characters
rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "")
// read flag arguments with CSV parser
ipStrSlice, err := readAsCSV(rmQuote.Replace(val))
if err != nil && err != io.EOF {
return err
}
// parse ip values into slice
out := make([]net.IP, 0, len(ipStrSlice))
for _, ipStr := range ipStrSlice {
ip := net.ParseIP(strings.TrimSpace(ipStr))
if ip == nil {
return fmt.Errorf("invalid string being converted to IP address: %s", ipStr)
}
out = append(out, ip)
}
if !s.changed {
*s.value = out
} else {
*s.value = append(*s.value, out...)
}
s.changed = true
return nil
}
// Type returns a string that uniquely represents this flag's type.
func (s *ipSliceValue) Type() string {
return "ipSlice"
}
// String defines a "native" format for this net.IP slice flag value.
func (s *ipSliceValue) String() string {
ipStrSlice := make([]string, len(*s.value))
for i, ip := range *s.value {
ipStrSlice[i] = ip.String()
}
out, _ := writeAsCSV(ipStrSlice)
return "[" + out + "]"
}
func (s *ipSliceValue) fromString(val string) (net.IP, error) {
return net.ParseIP(strings.TrimSpace(val)), nil
}
func (s *ipSliceValue) toString(val net.IP) string {
return val.String()
}
func (s *ipSliceValue) Append(val string) error {
i, err := s.fromString(val)
if err != nil {
return err
}
*s.value = append(*s.value, i)
return nil
}
func (s *ipSliceValue) Replace(val []string) error {
out := make([]net.IP, len(val))
for i, d := range val {
var err error
out[i], err = s.fromString(d)
if err != nil {
return err
}
}
*s.value = out
return nil
}
func (s *ipSliceValue) GetSlice() []string {
out := make([]string, len(*s.value))
for i, d := range *s.value {
out[i] = s.toString(d)
}
return out
}
func ipSliceConv(val string) (interface{}, error) {
val = strings.Trim(val, "[]")
// Empty string would cause a slice with one (empty) entry
if len(val) == 0 {
return []net.IP{}, nil
}
ss := strings.Split(val, ",")
out := make([]net.IP, len(ss))
for i, sval := range ss {
ip := net.ParseIP(strings.TrimSpace(sval))
if ip == nil {
return nil, fmt.Errorf("invalid string being converted to IP address: %s", sval)
}
out[i] = ip
}
return out, nil
}
// GetIPSlice returns the []net.IP value of a flag with the given name
func (f *FlagSet) GetIPSlice(name string) ([]net.IP, error) {
val, err := f.getFlagType(name, "ipSlice", ipSliceConv)
if err != nil {
return []net.IP{}, err
}
return val.([]net.IP), nil
}
// IPSliceVar defines a ipSlice flag with specified name, default value, and usage string.
// The argument p points to a []net.IP variable in which to store the value of the flag.
func (f *FlagSet) IPSliceVar(p *[]net.IP, name string, value []net.IP, usage string) {
f.VarP(newIPSliceValue(value, p), name, "", usage)
}
// IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) IPSliceVarP(p *[]net.IP, name, shorthand string, value []net.IP, usage string) {
f.VarP(newIPSliceValue(value, p), name, shorthand, usage)
}
// IPSliceVar defines a []net.IP flag with specified name, default value, and usage string.
// The argument p points to a []net.IP variable in which to store the value of the flag.
func IPSliceVar(p *[]net.IP, name string, value []net.IP, usage string) {
CommandLine.VarP(newIPSliceValue(value, p), name, "", usage)
}
// IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash.
func IPSliceVarP(p *[]net.IP, name, shorthand string, value []net.IP, usage string) {
CommandLine.VarP(newIPSliceValue(value, p), name, shorthand, usage)
}
// IPSlice defines a []net.IP flag with specified name, default value, and usage string.
// The return value is the address of a []net.IP variable that stores the value of that flag.
func (f *FlagSet) IPSlice(name string, value []net.IP, usage string) *[]net.IP {
p := []net.IP{}
f.IPSliceVarP(&p, name, "", value, usage)
return &p
}
// IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) IPSliceP(name, shorthand string, value []net.IP, usage string) *[]net.IP {
p := []net.IP{}
f.IPSliceVarP(&p, name, shorthand, value, usage)
return &p
}
// IPSlice defines a []net.IP flag with specified name, default value, and usage string.
// The return value is the address of a []net.IP variable that stores the value of the flag.
func IPSlice(name string, value []net.IP, usage string) *[]net.IP {
return CommandLine.IPSliceP(name, "", value, usage)
}
// IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash.
func IPSliceP(name, shorthand string, value []net.IP, usage string) *[]net.IP {
return CommandLine.IPSliceP(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/bool_slice.go | vendor/github.com/spf13/pflag/bool_slice.go | package pflag
import (
"io"
"strconv"
"strings"
)
// -- boolSlice Value
type boolSliceValue struct {
value *[]bool
changed bool
}
func newBoolSliceValue(val []bool, p *[]bool) *boolSliceValue {
bsv := new(boolSliceValue)
bsv.value = p
*bsv.value = val
return bsv
}
// Set converts, and assigns, the comma-separated boolean argument string representation as the []bool value of this flag.
// If Set is called on a flag that already has a []bool assigned, the newly converted values will be appended.
func (s *boolSliceValue) Set(val string) error {
// remove all quote characters
rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "")
// read flag arguments with CSV parser
boolStrSlice, err := readAsCSV(rmQuote.Replace(val))
if err != nil && err != io.EOF {
return err
}
// parse boolean values into slice
out := make([]bool, 0, len(boolStrSlice))
for _, boolStr := range boolStrSlice {
b, err := strconv.ParseBool(strings.TrimSpace(boolStr))
if err != nil {
return err
}
out = append(out, b)
}
if !s.changed {
*s.value = out
} else {
*s.value = append(*s.value, out...)
}
s.changed = true
return nil
}
// Type returns a string that uniquely represents this flag's type.
func (s *boolSliceValue) Type() string {
return "boolSlice"
}
// String defines a "native" format for this boolean slice flag value.
func (s *boolSliceValue) String() string {
boolStrSlice := make([]string, len(*s.value))
for i, b := range *s.value {
boolStrSlice[i] = strconv.FormatBool(b)
}
out, _ := writeAsCSV(boolStrSlice)
return "[" + out + "]"
}
func (s *boolSliceValue) fromString(val string) (bool, error) {
return strconv.ParseBool(val)
}
func (s *boolSliceValue) toString(val bool) string {
return strconv.FormatBool(val)
}
func (s *boolSliceValue) Append(val string) error {
i, err := s.fromString(val)
if err != nil {
return err
}
*s.value = append(*s.value, i)
return nil
}
func (s *boolSliceValue) Replace(val []string) error {
out := make([]bool, len(val))
for i, d := range val {
var err error
out[i], err = s.fromString(d)
if err != nil {
return err
}
}
*s.value = out
return nil
}
func (s *boolSliceValue) GetSlice() []string {
out := make([]string, len(*s.value))
for i, d := range *s.value {
out[i] = s.toString(d)
}
return out
}
func boolSliceConv(val string) (interface{}, error) {
val = strings.Trim(val, "[]")
// Empty string would cause a slice with one (empty) entry
if len(val) == 0 {
return []bool{}, nil
}
ss := strings.Split(val, ",")
out := make([]bool, len(ss))
for i, t := range ss {
var err error
out[i], err = strconv.ParseBool(t)
if err != nil {
return nil, err
}
}
return out, nil
}
// GetBoolSlice returns the []bool value of a flag with the given name.
func (f *FlagSet) GetBoolSlice(name string) ([]bool, error) {
val, err := f.getFlagType(name, "boolSlice", boolSliceConv)
if err != nil {
return []bool{}, err
}
return val.([]bool), nil
}
// BoolSliceVar defines a boolSlice flag with specified name, default value, and usage string.
// The argument p points to a []bool variable in which to store the value of the flag.
func (f *FlagSet) BoolSliceVar(p *[]bool, name string, value []bool, usage string) {
f.VarP(newBoolSliceValue(value, p), name, "", usage)
}
// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) {
f.VarP(newBoolSliceValue(value, p), name, shorthand, usage)
}
// BoolSliceVar defines a []bool flag with specified name, default value, and usage string.
// The argument p points to a []bool variable in which to store the value of the flag.
func BoolSliceVar(p *[]bool, name string, value []bool, usage string) {
CommandLine.VarP(newBoolSliceValue(value, p), name, "", usage)
}
// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash.
func BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) {
CommandLine.VarP(newBoolSliceValue(value, p), name, shorthand, usage)
}
// BoolSlice defines a []bool flag with specified name, default value, and usage string.
// The return value is the address of a []bool variable that stores the value of the flag.
func (f *FlagSet) BoolSlice(name string, value []bool, usage string) *[]bool {
p := []bool{}
f.BoolSliceVarP(&p, name, "", value, usage)
return &p
}
// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool {
p := []bool{}
f.BoolSliceVarP(&p, name, shorthand, value, usage)
return &p
}
// BoolSlice defines a []bool flag with specified name, default value, and usage string.
// The return value is the address of a []bool variable that stores the value of the flag.
func BoolSlice(name string, value []bool, usage string) *[]bool {
return CommandLine.BoolSliceP(name, "", value, usage)
}
// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash.
func BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool {
return CommandLine.BoolSliceP(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/bytes.go | vendor/github.com/spf13/pflag/bytes.go | package pflag
import (
"encoding/base64"
"encoding/hex"
"fmt"
"strings"
)
// BytesHex adapts []byte for use as a flag. Value of flag is HEX encoded
type bytesHexValue []byte
// String implements pflag.Value.String.
func (bytesHex bytesHexValue) String() string {
return fmt.Sprintf("%X", []byte(bytesHex))
}
// Set implements pflag.Value.Set.
func (bytesHex *bytesHexValue) Set(value string) error {
bin, err := hex.DecodeString(strings.TrimSpace(value))
if err != nil {
return err
}
*bytesHex = bin
return nil
}
// Type implements pflag.Value.Type.
func (*bytesHexValue) Type() string {
return "bytesHex"
}
func newBytesHexValue(val []byte, p *[]byte) *bytesHexValue {
*p = val
return (*bytesHexValue)(p)
}
func bytesHexConv(sval string) (interface{}, error) {
bin, err := hex.DecodeString(sval)
if err == nil {
return bin, nil
}
return nil, fmt.Errorf("invalid string being converted to Bytes: %s %s", sval, err)
}
// GetBytesHex return the []byte value of a flag with the given name
func (f *FlagSet) GetBytesHex(name string) ([]byte, error) {
val, err := f.getFlagType(name, "bytesHex", bytesHexConv)
if err != nil {
return []byte{}, err
}
return val.([]byte), nil
}
// BytesHexVar defines an []byte flag with specified name, default value, and usage string.
// The argument p points to an []byte variable in which to store the value of the flag.
func (f *FlagSet) BytesHexVar(p *[]byte, name string, value []byte, usage string) {
f.VarP(newBytesHexValue(value, p), name, "", usage)
}
// BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) BytesHexVarP(p *[]byte, name, shorthand string, value []byte, usage string) {
f.VarP(newBytesHexValue(value, p), name, shorthand, usage)
}
// BytesHexVar defines an []byte flag with specified name, default value, and usage string.
// The argument p points to an []byte variable in which to store the value of the flag.
func BytesHexVar(p *[]byte, name string, value []byte, usage string) {
CommandLine.VarP(newBytesHexValue(value, p), name, "", usage)
}
// BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash.
func BytesHexVarP(p *[]byte, name, shorthand string, value []byte, usage string) {
CommandLine.VarP(newBytesHexValue(value, p), name, shorthand, usage)
}
// BytesHex defines an []byte flag with specified name, default value, and usage string.
// The return value is the address of an []byte variable that stores the value of the flag.
func (f *FlagSet) BytesHex(name string, value []byte, usage string) *[]byte {
p := new([]byte)
f.BytesHexVarP(p, name, "", value, usage)
return p
}
// BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) BytesHexP(name, shorthand string, value []byte, usage string) *[]byte {
p := new([]byte)
f.BytesHexVarP(p, name, shorthand, value, usage)
return p
}
// BytesHex defines an []byte flag with specified name, default value, and usage string.
// The return value is the address of an []byte variable that stores the value of the flag.
func BytesHex(name string, value []byte, usage string) *[]byte {
return CommandLine.BytesHexP(name, "", value, usage)
}
// BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash.
func BytesHexP(name, shorthand string, value []byte, usage string) *[]byte {
return CommandLine.BytesHexP(name, shorthand, value, usage)
}
// BytesBase64 adapts []byte for use as a flag. Value of flag is Base64 encoded
type bytesBase64Value []byte
// String implements pflag.Value.String.
func (bytesBase64 bytesBase64Value) String() string {
return base64.StdEncoding.EncodeToString([]byte(bytesBase64))
}
// Set implements pflag.Value.Set.
func (bytesBase64 *bytesBase64Value) Set(value string) error {
bin, err := base64.StdEncoding.DecodeString(strings.TrimSpace(value))
if err != nil {
return err
}
*bytesBase64 = bin
return nil
}
// Type implements pflag.Value.Type.
func (*bytesBase64Value) Type() string {
return "bytesBase64"
}
func newBytesBase64Value(val []byte, p *[]byte) *bytesBase64Value {
*p = val
return (*bytesBase64Value)(p)
}
func bytesBase64ValueConv(sval string) (interface{}, error) {
bin, err := base64.StdEncoding.DecodeString(sval)
if err == nil {
return bin, nil
}
return nil, fmt.Errorf("invalid string being converted to Bytes: %s %s", sval, err)
}
// GetBytesBase64 return the []byte value of a flag with the given name
func (f *FlagSet) GetBytesBase64(name string) ([]byte, error) {
val, err := f.getFlagType(name, "bytesBase64", bytesBase64ValueConv)
if err != nil {
return []byte{}, err
}
return val.([]byte), nil
}
// BytesBase64Var defines an []byte flag with specified name, default value, and usage string.
// The argument p points to an []byte variable in which to store the value of the flag.
func (f *FlagSet) BytesBase64Var(p *[]byte, name string, value []byte, usage string) {
f.VarP(newBytesBase64Value(value, p), name, "", usage)
}
// BytesBase64VarP is like BytesBase64Var, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) BytesBase64VarP(p *[]byte, name, shorthand string, value []byte, usage string) {
f.VarP(newBytesBase64Value(value, p), name, shorthand, usage)
}
// BytesBase64Var defines an []byte flag with specified name, default value, and usage string.
// The argument p points to an []byte variable in which to store the value of the flag.
func BytesBase64Var(p *[]byte, name string, value []byte, usage string) {
CommandLine.VarP(newBytesBase64Value(value, p), name, "", usage)
}
// BytesBase64VarP is like BytesBase64Var, but accepts a shorthand letter that can be used after a single dash.
func BytesBase64VarP(p *[]byte, name, shorthand string, value []byte, usage string) {
CommandLine.VarP(newBytesBase64Value(value, p), name, shorthand, usage)
}
// BytesBase64 defines an []byte flag with specified name, default value, and usage string.
// The return value is the address of an []byte variable that stores the value of the flag.
func (f *FlagSet) BytesBase64(name string, value []byte, usage string) *[]byte {
p := new([]byte)
f.BytesBase64VarP(p, name, "", value, usage)
return p
}
// BytesBase64P is like BytesBase64, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) BytesBase64P(name, shorthand string, value []byte, usage string) *[]byte {
p := new([]byte)
f.BytesBase64VarP(p, name, shorthand, value, usage)
return p
}
// BytesBase64 defines an []byte flag with specified name, default value, and usage string.
// The return value is the address of an []byte variable that stores the value of the flag.
func BytesBase64(name string, value []byte, usage string) *[]byte {
return CommandLine.BytesBase64P(name, "", value, usage)
}
// BytesBase64P is like BytesBase64, but accepts a shorthand letter that can be used after a single dash.
func BytesBase64P(name, shorthand string, value []byte, usage string) *[]byte {
return CommandLine.BytesBase64P(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/uint8.go | vendor/github.com/spf13/pflag/uint8.go | package pflag
import "strconv"
// -- uint8 Value
type uint8Value uint8
func newUint8Value(val uint8, p *uint8) *uint8Value {
*p = val
return (*uint8Value)(p)
}
func (i *uint8Value) Set(s string) error {
v, err := strconv.ParseUint(s, 0, 8)
*i = uint8Value(v)
return err
}
func (i *uint8Value) Type() string {
return "uint8"
}
func (i *uint8Value) String() string { return strconv.FormatUint(uint64(*i), 10) }
func uint8Conv(sval string) (interface{}, error) {
v, err := strconv.ParseUint(sval, 0, 8)
if err != nil {
return 0, err
}
return uint8(v), nil
}
// GetUint8 return the uint8 value of a flag with the given name
func (f *FlagSet) GetUint8(name string) (uint8, error) {
val, err := f.getFlagType(name, "uint8", uint8Conv)
if err != nil {
return 0, err
}
return val.(uint8), nil
}
// Uint8Var defines a uint8 flag with specified name, default value, and usage string.
// The argument p points to a uint8 variable in which to store the value of the flag.
func (f *FlagSet) Uint8Var(p *uint8, name string, value uint8, usage string) {
f.VarP(newUint8Value(value, p), name, "", usage)
}
// Uint8VarP is like Uint8Var, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Uint8VarP(p *uint8, name, shorthand string, value uint8, usage string) {
f.VarP(newUint8Value(value, p), name, shorthand, usage)
}
// Uint8Var defines a uint8 flag with specified name, default value, and usage string.
// The argument p points to a uint8 variable in which to store the value of the flag.
func Uint8Var(p *uint8, name string, value uint8, usage string) {
CommandLine.VarP(newUint8Value(value, p), name, "", usage)
}
// Uint8VarP is like Uint8Var, but accepts a shorthand letter that can be used after a single dash.
func Uint8VarP(p *uint8, name, shorthand string, value uint8, usage string) {
CommandLine.VarP(newUint8Value(value, p), name, shorthand, usage)
}
// Uint8 defines a uint8 flag with specified name, default value, and usage string.
// The return value is the address of a uint8 variable that stores the value of the flag.
func (f *FlagSet) Uint8(name string, value uint8, usage string) *uint8 {
p := new(uint8)
f.Uint8VarP(p, name, "", value, usage)
return p
}
// Uint8P is like Uint8, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Uint8P(name, shorthand string, value uint8, usage string) *uint8 {
p := new(uint8)
f.Uint8VarP(p, name, shorthand, value, usage)
return p
}
// Uint8 defines a uint8 flag with specified name, default value, and usage string.
// The return value is the address of a uint8 variable that stores the value of the flag.
func Uint8(name string, value uint8, usage string) *uint8 {
return CommandLine.Uint8P(name, "", value, usage)
}
// Uint8P is like Uint8, but accepts a shorthand letter that can be used after a single dash.
func Uint8P(name, shorthand string, value uint8, usage string) *uint8 {
return CommandLine.Uint8P(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/string.go | vendor/github.com/spf13/pflag/string.go | package pflag
// -- string Value
type stringValue string
func newStringValue(val string, p *string) *stringValue {
*p = val
return (*stringValue)(p)
}
func (s *stringValue) Set(val string) error {
*s = stringValue(val)
return nil
}
func (s *stringValue) Type() string {
return "string"
}
func (s *stringValue) String() string { return string(*s) }
func stringConv(sval string) (interface{}, error) {
return sval, nil
}
// GetString return the string value of a flag with the given name
func (f *FlagSet) GetString(name string) (string, error) {
val, err := f.getFlagType(name, "string", stringConv)
if err != nil {
return "", err
}
return val.(string), nil
}
// StringVar defines a string flag with specified name, default value, and usage string.
// The argument p points to a string variable in which to store the value of the flag.
func (f *FlagSet) StringVar(p *string, name string, value string, usage string) {
f.VarP(newStringValue(value, p), name, "", usage)
}
// StringVarP is like StringVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) StringVarP(p *string, name, shorthand string, value string, usage string) {
f.VarP(newStringValue(value, p), name, shorthand, usage)
}
// StringVar defines a string flag with specified name, default value, and usage string.
// The argument p points to a string variable in which to store the value of the flag.
func StringVar(p *string, name string, value string, usage string) {
CommandLine.VarP(newStringValue(value, p), name, "", usage)
}
// StringVarP is like StringVar, but accepts a shorthand letter that can be used after a single dash.
func StringVarP(p *string, name, shorthand string, value string, usage string) {
CommandLine.VarP(newStringValue(value, p), name, shorthand, usage)
}
// String defines a string flag with specified name, default value, and usage string.
// The return value is the address of a string variable that stores the value of the flag.
func (f *FlagSet) String(name string, value string, usage string) *string {
p := new(string)
f.StringVarP(p, name, "", value, usage)
return p
}
// StringP is like String, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) StringP(name, shorthand string, value string, usage string) *string {
p := new(string)
f.StringVarP(p, name, shorthand, value, usage)
return p
}
// String defines a string flag with specified name, default value, and usage string.
// The return value is the address of a string variable that stores the value of the flag.
func String(name string, value string, usage string) *string {
return CommandLine.StringP(name, "", value, usage)
}
// StringP is like String, but accepts a shorthand letter that can be used after a single dash.
func StringP(name, shorthand string, value string, usage string) *string {
return CommandLine.StringP(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/int.go | vendor/github.com/spf13/pflag/int.go | package pflag
import "strconv"
// -- int Value
type intValue int
func newIntValue(val int, p *int) *intValue {
*p = val
return (*intValue)(p)
}
func (i *intValue) Set(s string) error {
v, err := strconv.ParseInt(s, 0, 64)
*i = intValue(v)
return err
}
func (i *intValue) Type() string {
return "int"
}
func (i *intValue) String() string { return strconv.Itoa(int(*i)) }
func intConv(sval string) (interface{}, error) {
return strconv.Atoi(sval)
}
// GetInt return the int value of a flag with the given name
func (f *FlagSet) GetInt(name string) (int, error) {
val, err := f.getFlagType(name, "int", intConv)
if err != nil {
return 0, err
}
return val.(int), nil
}
// IntVar defines an int flag with specified name, default value, and usage string.
// The argument p points to an int variable in which to store the value of the flag.
func (f *FlagSet) IntVar(p *int, name string, value int, usage string) {
f.VarP(newIntValue(value, p), name, "", usage)
}
// IntVarP is like IntVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) IntVarP(p *int, name, shorthand string, value int, usage string) {
f.VarP(newIntValue(value, p), name, shorthand, usage)
}
// IntVar defines an int flag with specified name, default value, and usage string.
// The argument p points to an int variable in which to store the value of the flag.
func IntVar(p *int, name string, value int, usage string) {
CommandLine.VarP(newIntValue(value, p), name, "", usage)
}
// IntVarP is like IntVar, but accepts a shorthand letter that can be used after a single dash.
func IntVarP(p *int, name, shorthand string, value int, usage string) {
CommandLine.VarP(newIntValue(value, p), name, shorthand, usage)
}
// Int defines an int flag with specified name, default value, and usage string.
// The return value is the address of an int variable that stores the value of the flag.
func (f *FlagSet) Int(name string, value int, usage string) *int {
p := new(int)
f.IntVarP(p, name, "", value, usage)
return p
}
// IntP is like Int, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) IntP(name, shorthand string, value int, usage string) *int {
p := new(int)
f.IntVarP(p, name, shorthand, value, usage)
return p
}
// Int defines an int flag with specified name, default value, and usage string.
// The return value is the address of an int variable that stores the value of the flag.
func Int(name string, value int, usage string) *int {
return CommandLine.IntP(name, "", value, usage)
}
// IntP is like Int, but accepts a shorthand letter that can be used after a single dash.
func IntP(name, shorthand string, value int, usage string) *int {
return CommandLine.IntP(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/golangflag.go | vendor/github.com/spf13/pflag/golangflag.go | // Copyright 2009 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 pflag
import (
goflag "flag"
"reflect"
"strings"
)
// flagValueWrapper implements pflag.Value around a flag.Value. The main
// difference here is the addition of the Type method that returns a string
// name of the type. As this is generally unknown, we approximate that with
// reflection.
type flagValueWrapper struct {
inner goflag.Value
flagType string
}
// We are just copying the boolFlag interface out of goflag as that is what
// they use to decide if a flag should get "true" when no arg is given.
type goBoolFlag interface {
goflag.Value
IsBoolFlag() bool
}
func wrapFlagValue(v goflag.Value) Value {
// If the flag.Value happens to also be a pflag.Value, just use it directly.
if pv, ok := v.(Value); ok {
return pv
}
pv := &flagValueWrapper{
inner: v,
}
t := reflect.TypeOf(v)
if t.Kind() == reflect.Interface || t.Kind() == reflect.Ptr {
t = t.Elem()
}
pv.flagType = strings.TrimSuffix(t.Name(), "Value")
return pv
}
func (v *flagValueWrapper) String() string {
return v.inner.String()
}
func (v *flagValueWrapper) Set(s string) error {
return v.inner.Set(s)
}
func (v *flagValueWrapper) Type() string {
return v.flagType
}
// PFlagFromGoFlag will return a *pflag.Flag given a *flag.Flag
// If the *flag.Flag.Name was a single character (ex: `v`) it will be accessiblei
// with both `-v` and `--v` in flags. If the golang flag was more than a single
// character (ex: `verbose`) it will only be accessible via `--verbose`
func PFlagFromGoFlag(goflag *goflag.Flag) *Flag {
// Remember the default value as a string; it won't change.
flag := &Flag{
Name: goflag.Name,
Usage: goflag.Usage,
Value: wrapFlagValue(goflag.Value),
// Looks like golang flags don't set DefValue correctly :-(
//DefValue: goflag.DefValue,
DefValue: goflag.Value.String(),
}
// Ex: if the golang flag was -v, allow both -v and --v to work
if len(flag.Name) == 1 {
flag.Shorthand = flag.Name
}
if fv, ok := goflag.Value.(goBoolFlag); ok && fv.IsBoolFlag() {
flag.NoOptDefVal = "true"
}
return flag
}
// AddGoFlag will add the given *flag.Flag to the pflag.FlagSet
func (f *FlagSet) AddGoFlag(goflag *goflag.Flag) {
if f.Lookup(goflag.Name) != nil {
return
}
newflag := PFlagFromGoFlag(goflag)
f.AddFlag(newflag)
}
// AddGoFlagSet will add the given *flag.FlagSet to the pflag.FlagSet
func (f *FlagSet) AddGoFlagSet(newSet *goflag.FlagSet) {
if newSet == nil {
return
}
newSet.VisitAll(func(goflag *goflag.Flag) {
f.AddGoFlag(goflag)
})
if f.addedGoFlagSets == nil {
f.addedGoFlagSets = make([]*goflag.FlagSet, 0)
}
f.addedGoFlagSets = append(f.addedGoFlagSets, newSet)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/int64_slice.go | vendor/github.com/spf13/pflag/int64_slice.go | package pflag
import (
"fmt"
"strconv"
"strings"
)
// -- int64Slice Value
type int64SliceValue struct {
value *[]int64
changed bool
}
func newInt64SliceValue(val []int64, p *[]int64) *int64SliceValue {
isv := new(int64SliceValue)
isv.value = p
*isv.value = val
return isv
}
func (s *int64SliceValue) Set(val string) error {
ss := strings.Split(val, ",")
out := make([]int64, len(ss))
for i, d := range ss {
var err error
out[i], err = strconv.ParseInt(d, 0, 64)
if err != nil {
return err
}
}
if !s.changed {
*s.value = out
} else {
*s.value = append(*s.value, out...)
}
s.changed = true
return nil
}
func (s *int64SliceValue) Type() string {
return "int64Slice"
}
func (s *int64SliceValue) String() string {
out := make([]string, len(*s.value))
for i, d := range *s.value {
out[i] = fmt.Sprintf("%d", d)
}
return "[" + strings.Join(out, ",") + "]"
}
func (s *int64SliceValue) fromString(val string) (int64, error) {
return strconv.ParseInt(val, 0, 64)
}
func (s *int64SliceValue) toString(val int64) string {
return fmt.Sprintf("%d", val)
}
func (s *int64SliceValue) Append(val string) error {
i, err := s.fromString(val)
if err != nil {
return err
}
*s.value = append(*s.value, i)
return nil
}
func (s *int64SliceValue) Replace(val []string) error {
out := make([]int64, len(val))
for i, d := range val {
var err error
out[i], err = s.fromString(d)
if err != nil {
return err
}
}
*s.value = out
return nil
}
func (s *int64SliceValue) GetSlice() []string {
out := make([]string, len(*s.value))
for i, d := range *s.value {
out[i] = s.toString(d)
}
return out
}
func int64SliceConv(val string) (interface{}, error) {
val = strings.Trim(val, "[]")
// Empty string would cause a slice with one (empty) entry
if len(val) == 0 {
return []int64{}, nil
}
ss := strings.Split(val, ",")
out := make([]int64, len(ss))
for i, d := range ss {
var err error
out[i], err = strconv.ParseInt(d, 0, 64)
if err != nil {
return nil, err
}
}
return out, nil
}
// GetInt64Slice return the []int64 value of a flag with the given name
func (f *FlagSet) GetInt64Slice(name string) ([]int64, error) {
val, err := f.getFlagType(name, "int64Slice", int64SliceConv)
if err != nil {
return []int64{}, err
}
return val.([]int64), nil
}
// Int64SliceVar defines a int64Slice flag with specified name, default value, and usage string.
// The argument p points to a []int64 variable in which to store the value of the flag.
func (f *FlagSet) Int64SliceVar(p *[]int64, name string, value []int64, usage string) {
f.VarP(newInt64SliceValue(value, p), name, "", usage)
}
// Int64SliceVarP is like Int64SliceVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Int64SliceVarP(p *[]int64, name, shorthand string, value []int64, usage string) {
f.VarP(newInt64SliceValue(value, p), name, shorthand, usage)
}
// Int64SliceVar defines a int64[] flag with specified name, default value, and usage string.
// The argument p points to a int64[] variable in which to store the value of the flag.
func Int64SliceVar(p *[]int64, name string, value []int64, usage string) {
CommandLine.VarP(newInt64SliceValue(value, p), name, "", usage)
}
// Int64SliceVarP is like Int64SliceVar, but accepts a shorthand letter that can be used after a single dash.
func Int64SliceVarP(p *[]int64, name, shorthand string, value []int64, usage string) {
CommandLine.VarP(newInt64SliceValue(value, p), name, shorthand, usage)
}
// Int64Slice defines a []int64 flag with specified name, default value, and usage string.
// The return value is the address of a []int64 variable that stores the value of the flag.
func (f *FlagSet) Int64Slice(name string, value []int64, usage string) *[]int64 {
p := []int64{}
f.Int64SliceVarP(&p, name, "", value, usage)
return &p
}
// Int64SliceP is like Int64Slice, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Int64SliceP(name, shorthand string, value []int64, usage string) *[]int64 {
p := []int64{}
f.Int64SliceVarP(&p, name, shorthand, value, usage)
return &p
}
// Int64Slice defines a []int64 flag with specified name, default value, and usage string.
// The return value is the address of a []int64 variable that stores the value of the flag.
func Int64Slice(name string, value []int64, usage string) *[]int64 {
return CommandLine.Int64SliceP(name, "", value, usage)
}
// Int64SliceP is like Int64Slice, but accepts a shorthand letter that can be used after a single dash.
func Int64SliceP(name, shorthand string, value []int64, usage string) *[]int64 {
return CommandLine.Int64SliceP(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/float64.go | vendor/github.com/spf13/pflag/float64.go | package pflag
import "strconv"
// -- float64 Value
type float64Value float64
func newFloat64Value(val float64, p *float64) *float64Value {
*p = val
return (*float64Value)(p)
}
func (f *float64Value) Set(s string) error {
v, err := strconv.ParseFloat(s, 64)
*f = float64Value(v)
return err
}
func (f *float64Value) Type() string {
return "float64"
}
func (f *float64Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 64) }
func float64Conv(sval string) (interface{}, error) {
return strconv.ParseFloat(sval, 64)
}
// GetFloat64 return the float64 value of a flag with the given name
func (f *FlagSet) GetFloat64(name string) (float64, error) {
val, err := f.getFlagType(name, "float64", float64Conv)
if err != nil {
return 0, err
}
return val.(float64), nil
}
// Float64Var defines a float64 flag with specified name, default value, and usage string.
// The argument p points to a float64 variable in which to store the value of the flag.
func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string) {
f.VarP(newFloat64Value(value, p), name, "", usage)
}
// Float64VarP is like Float64Var, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Float64VarP(p *float64, name, shorthand string, value float64, usage string) {
f.VarP(newFloat64Value(value, p), name, shorthand, usage)
}
// Float64Var defines a float64 flag with specified name, default value, and usage string.
// The argument p points to a float64 variable in which to store the value of the flag.
func Float64Var(p *float64, name string, value float64, usage string) {
CommandLine.VarP(newFloat64Value(value, p), name, "", usage)
}
// Float64VarP is like Float64Var, but accepts a shorthand letter that can be used after a single dash.
func Float64VarP(p *float64, name, shorthand string, value float64, usage string) {
CommandLine.VarP(newFloat64Value(value, p), name, shorthand, usage)
}
// Float64 defines a float64 flag with specified name, default value, and usage string.
// The return value is the address of a float64 variable that stores the value of the flag.
func (f *FlagSet) Float64(name string, value float64, usage string) *float64 {
p := new(float64)
f.Float64VarP(p, name, "", value, usage)
return p
}
// Float64P is like Float64, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Float64P(name, shorthand string, value float64, usage string) *float64 {
p := new(float64)
f.Float64VarP(p, name, shorthand, value, usage)
return p
}
// Float64 defines a float64 flag with specified name, default value, and usage string.
// The return value is the address of a float64 variable that stores the value of the flag.
func Float64(name string, value float64, usage string) *float64 {
return CommandLine.Float64P(name, "", value, usage)
}
// Float64P is like Float64, but accepts a shorthand letter that can be used after a single dash.
func Float64P(name, shorthand string, value float64, usage string) *float64 {
return CommandLine.Float64P(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/uint64.go | vendor/github.com/spf13/pflag/uint64.go | package pflag
import "strconv"
// -- uint64 Value
type uint64Value uint64
func newUint64Value(val uint64, p *uint64) *uint64Value {
*p = val
return (*uint64Value)(p)
}
func (i *uint64Value) Set(s string) error {
v, err := strconv.ParseUint(s, 0, 64)
*i = uint64Value(v)
return err
}
func (i *uint64Value) Type() string {
return "uint64"
}
func (i *uint64Value) String() string { return strconv.FormatUint(uint64(*i), 10) }
func uint64Conv(sval string) (interface{}, error) {
v, err := strconv.ParseUint(sval, 0, 64)
if err != nil {
return 0, err
}
return uint64(v), nil
}
// GetUint64 return the uint64 value of a flag with the given name
func (f *FlagSet) GetUint64(name string) (uint64, error) {
val, err := f.getFlagType(name, "uint64", uint64Conv)
if err != nil {
return 0, err
}
return val.(uint64), nil
}
// Uint64Var defines a uint64 flag with specified name, default value, and usage string.
// The argument p points to a uint64 variable in which to store the value of the flag.
func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) {
f.VarP(newUint64Value(value, p), name, "", usage)
}
// Uint64VarP is like Uint64Var, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) {
f.VarP(newUint64Value(value, p), name, shorthand, usage)
}
// Uint64Var defines a uint64 flag with specified name, default value, and usage string.
// The argument p points to a uint64 variable in which to store the value of the flag.
func Uint64Var(p *uint64, name string, value uint64, usage string) {
CommandLine.VarP(newUint64Value(value, p), name, "", usage)
}
// Uint64VarP is like Uint64Var, but accepts a shorthand letter that can be used after a single dash.
func Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) {
CommandLine.VarP(newUint64Value(value, p), name, shorthand, usage)
}
// Uint64 defines a uint64 flag with specified name, default value, and usage string.
// The return value is the address of a uint64 variable that stores the value of the flag.
func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 {
p := new(uint64)
f.Uint64VarP(p, name, "", value, usage)
return p
}
// Uint64P is like Uint64, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Uint64P(name, shorthand string, value uint64, usage string) *uint64 {
p := new(uint64)
f.Uint64VarP(p, name, shorthand, value, usage)
return p
}
// Uint64 defines a uint64 flag with specified name, default value, and usage string.
// The return value is the address of a uint64 variable that stores the value of the flag.
func Uint64(name string, value uint64, usage string) *uint64 {
return CommandLine.Uint64P(name, "", value, usage)
}
// Uint64P is like Uint64, but accepts a shorthand letter that can be used after a single dash.
func Uint64P(name, shorthand string, value uint64, usage string) *uint64 {
return CommandLine.Uint64P(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/int32.go | vendor/github.com/spf13/pflag/int32.go | package pflag
import "strconv"
// -- int32 Value
type int32Value int32
func newInt32Value(val int32, p *int32) *int32Value {
*p = val
return (*int32Value)(p)
}
func (i *int32Value) Set(s string) error {
v, err := strconv.ParseInt(s, 0, 32)
*i = int32Value(v)
return err
}
func (i *int32Value) Type() string {
return "int32"
}
func (i *int32Value) String() string { return strconv.FormatInt(int64(*i), 10) }
func int32Conv(sval string) (interface{}, error) {
v, err := strconv.ParseInt(sval, 0, 32)
if err != nil {
return 0, err
}
return int32(v), nil
}
// GetInt32 return the int32 value of a flag with the given name
func (f *FlagSet) GetInt32(name string) (int32, error) {
val, err := f.getFlagType(name, "int32", int32Conv)
if err != nil {
return 0, err
}
return val.(int32), nil
}
// Int32Var defines an int32 flag with specified name, default value, and usage string.
// The argument p points to an int32 variable in which to store the value of the flag.
func (f *FlagSet) Int32Var(p *int32, name string, value int32, usage string) {
f.VarP(newInt32Value(value, p), name, "", usage)
}
// Int32VarP is like Int32Var, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Int32VarP(p *int32, name, shorthand string, value int32, usage string) {
f.VarP(newInt32Value(value, p), name, shorthand, usage)
}
// Int32Var defines an int32 flag with specified name, default value, and usage string.
// The argument p points to an int32 variable in which to store the value of the flag.
func Int32Var(p *int32, name string, value int32, usage string) {
CommandLine.VarP(newInt32Value(value, p), name, "", usage)
}
// Int32VarP is like Int32Var, but accepts a shorthand letter that can be used after a single dash.
func Int32VarP(p *int32, name, shorthand string, value int32, usage string) {
CommandLine.VarP(newInt32Value(value, p), name, shorthand, usage)
}
// Int32 defines an int32 flag with specified name, default value, and usage string.
// The return value is the address of an int32 variable that stores the value of the flag.
func (f *FlagSet) Int32(name string, value int32, usage string) *int32 {
p := new(int32)
f.Int32VarP(p, name, "", value, usage)
return p
}
// Int32P is like Int32, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Int32P(name, shorthand string, value int32, usage string) *int32 {
p := new(int32)
f.Int32VarP(p, name, shorthand, value, usage)
return p
}
// Int32 defines an int32 flag with specified name, default value, and usage string.
// The return value is the address of an int32 variable that stores the value of the flag.
func Int32(name string, value int32, usage string) *int32 {
return CommandLine.Int32P(name, "", value, usage)
}
// Int32P is like Int32, but accepts a shorthand letter that can be used after a single dash.
func Int32P(name, shorthand string, value int32, usage string) *int32 {
return CommandLine.Int32P(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/string_to_int64.go | vendor/github.com/spf13/pflag/string_to_int64.go | package pflag
import (
"bytes"
"fmt"
"strconv"
"strings"
)
// -- stringToInt64 Value
type stringToInt64Value struct {
value *map[string]int64
changed bool
}
func newStringToInt64Value(val map[string]int64, p *map[string]int64) *stringToInt64Value {
ssv := new(stringToInt64Value)
ssv.value = p
*ssv.value = val
return ssv
}
// Format: a=1,b=2
func (s *stringToInt64Value) Set(val string) error {
ss := strings.Split(val, ",")
out := make(map[string]int64, len(ss))
for _, pair := range ss {
kv := strings.SplitN(pair, "=", 2)
if len(kv) != 2 {
return fmt.Errorf("%s must be formatted as key=value", pair)
}
var err error
out[kv[0]], err = strconv.ParseInt(kv[1], 10, 64)
if err != nil {
return err
}
}
if !s.changed {
*s.value = out
} else {
for k, v := range out {
(*s.value)[k] = v
}
}
s.changed = true
return nil
}
func (s *stringToInt64Value) Type() string {
return "stringToInt64"
}
func (s *stringToInt64Value) String() string {
var buf bytes.Buffer
i := 0
for k, v := range *s.value {
if i > 0 {
buf.WriteRune(',')
}
buf.WriteString(k)
buf.WriteRune('=')
buf.WriteString(strconv.FormatInt(v, 10))
i++
}
return "[" + buf.String() + "]"
}
func stringToInt64Conv(val string) (interface{}, error) {
val = strings.Trim(val, "[]")
// An empty string would cause an empty map
if len(val) == 0 {
return map[string]int64{}, nil
}
ss := strings.Split(val, ",")
out := make(map[string]int64, len(ss))
for _, pair := range ss {
kv := strings.SplitN(pair, "=", 2)
if len(kv) != 2 {
return nil, fmt.Errorf("%s must be formatted as key=value", pair)
}
var err error
out[kv[0]], err = strconv.ParseInt(kv[1], 10, 64)
if err != nil {
return nil, err
}
}
return out, nil
}
// GetStringToInt64 return the map[string]int64 value of a flag with the given name
func (f *FlagSet) GetStringToInt64(name string) (map[string]int64, error) {
val, err := f.getFlagType(name, "stringToInt64", stringToInt64Conv)
if err != nil {
return map[string]int64{}, err
}
return val.(map[string]int64), nil
}
// StringToInt64Var defines a string flag with specified name, default value, and usage string.
// The argument p point64s to a map[string]int64 variable in which to store the values of the multiple flags.
// The value of each argument will not try to be separated by comma
func (f *FlagSet) StringToInt64Var(p *map[string]int64, name string, value map[string]int64, usage string) {
f.VarP(newStringToInt64Value(value, p), name, "", usage)
}
// StringToInt64VarP is like StringToInt64Var, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) StringToInt64VarP(p *map[string]int64, name, shorthand string, value map[string]int64, usage string) {
f.VarP(newStringToInt64Value(value, p), name, shorthand, usage)
}
// StringToInt64Var defines a string flag with specified name, default value, and usage string.
// The argument p point64s to a map[string]int64 variable in which to store the value of the flag.
// The value of each argument will not try to be separated by comma
func StringToInt64Var(p *map[string]int64, name string, value map[string]int64, usage string) {
CommandLine.VarP(newStringToInt64Value(value, p), name, "", usage)
}
// StringToInt64VarP is like StringToInt64Var, but accepts a shorthand letter that can be used after a single dash.
func StringToInt64VarP(p *map[string]int64, name, shorthand string, value map[string]int64, usage string) {
CommandLine.VarP(newStringToInt64Value(value, p), name, shorthand, usage)
}
// StringToInt64 defines a string flag with specified name, default value, and usage string.
// The return value is the address of a map[string]int64 variable that stores the value of the flag.
// The value of each argument will not try to be separated by comma
func (f *FlagSet) StringToInt64(name string, value map[string]int64, usage string) *map[string]int64 {
p := map[string]int64{}
f.StringToInt64VarP(&p, name, "", value, usage)
return &p
}
// StringToInt64P is like StringToInt64, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) StringToInt64P(name, shorthand string, value map[string]int64, usage string) *map[string]int64 {
p := map[string]int64{}
f.StringToInt64VarP(&p, name, shorthand, value, usage)
return &p
}
// StringToInt64 defines a string flag with specified name, default value, and usage string.
// The return value is the address of a map[string]int64 variable that stores the value of the flag.
// The value of each argument will not try to be separated by comma
func StringToInt64(name string, value map[string]int64, usage string) *map[string]int64 {
return CommandLine.StringToInt64P(name, "", value, usage)
}
// StringToInt64P is like StringToInt64, but accepts a shorthand letter that can be used after a single dash.
func StringToInt64P(name, shorthand string, value map[string]int64, usage string) *map[string]int64 {
return CommandLine.StringToInt64P(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/float32_slice.go | vendor/github.com/spf13/pflag/float32_slice.go | package pflag
import (
"fmt"
"strconv"
"strings"
)
// -- float32Slice Value
type float32SliceValue struct {
value *[]float32
changed bool
}
func newFloat32SliceValue(val []float32, p *[]float32) *float32SliceValue {
isv := new(float32SliceValue)
isv.value = p
*isv.value = val
return isv
}
func (s *float32SliceValue) Set(val string) error {
ss := strings.Split(val, ",")
out := make([]float32, len(ss))
for i, d := range ss {
var err error
var temp64 float64
temp64, err = strconv.ParseFloat(d, 32)
if err != nil {
return err
}
out[i] = float32(temp64)
}
if !s.changed {
*s.value = out
} else {
*s.value = append(*s.value, out...)
}
s.changed = true
return nil
}
func (s *float32SliceValue) Type() string {
return "float32Slice"
}
func (s *float32SliceValue) String() string {
out := make([]string, len(*s.value))
for i, d := range *s.value {
out[i] = fmt.Sprintf("%f", d)
}
return "[" + strings.Join(out, ",") + "]"
}
func (s *float32SliceValue) fromString(val string) (float32, error) {
t64, err := strconv.ParseFloat(val, 32)
if err != nil {
return 0, err
}
return float32(t64), nil
}
func (s *float32SliceValue) toString(val float32) string {
return fmt.Sprintf("%f", val)
}
func (s *float32SliceValue) Append(val string) error {
i, err := s.fromString(val)
if err != nil {
return err
}
*s.value = append(*s.value, i)
return nil
}
func (s *float32SliceValue) Replace(val []string) error {
out := make([]float32, len(val))
for i, d := range val {
var err error
out[i], err = s.fromString(d)
if err != nil {
return err
}
}
*s.value = out
return nil
}
func (s *float32SliceValue) GetSlice() []string {
out := make([]string, len(*s.value))
for i, d := range *s.value {
out[i] = s.toString(d)
}
return out
}
func float32SliceConv(val string) (interface{}, error) {
val = strings.Trim(val, "[]")
// Empty string would cause a slice with one (empty) entry
if len(val) == 0 {
return []float32{}, nil
}
ss := strings.Split(val, ",")
out := make([]float32, len(ss))
for i, d := range ss {
var err error
var temp64 float64
temp64, err = strconv.ParseFloat(d, 32)
if err != nil {
return nil, err
}
out[i] = float32(temp64)
}
return out, nil
}
// GetFloat32Slice return the []float32 value of a flag with the given name
func (f *FlagSet) GetFloat32Slice(name string) ([]float32, error) {
val, err := f.getFlagType(name, "float32Slice", float32SliceConv)
if err != nil {
return []float32{}, err
}
return val.([]float32), nil
}
// Float32SliceVar defines a float32Slice flag with specified name, default value, and usage string.
// The argument p points to a []float32 variable in which to store the value of the flag.
func (f *FlagSet) Float32SliceVar(p *[]float32, name string, value []float32, usage string) {
f.VarP(newFloat32SliceValue(value, p), name, "", usage)
}
// Float32SliceVarP is like Float32SliceVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Float32SliceVarP(p *[]float32, name, shorthand string, value []float32, usage string) {
f.VarP(newFloat32SliceValue(value, p), name, shorthand, usage)
}
// Float32SliceVar defines a float32[] flag with specified name, default value, and usage string.
// The argument p points to a float32[] variable in which to store the value of the flag.
func Float32SliceVar(p *[]float32, name string, value []float32, usage string) {
CommandLine.VarP(newFloat32SliceValue(value, p), name, "", usage)
}
// Float32SliceVarP is like Float32SliceVar, but accepts a shorthand letter that can be used after a single dash.
func Float32SliceVarP(p *[]float32, name, shorthand string, value []float32, usage string) {
CommandLine.VarP(newFloat32SliceValue(value, p), name, shorthand, usage)
}
// Float32Slice defines a []float32 flag with specified name, default value, and usage string.
// The return value is the address of a []float32 variable that stores the value of the flag.
func (f *FlagSet) Float32Slice(name string, value []float32, usage string) *[]float32 {
p := []float32{}
f.Float32SliceVarP(&p, name, "", value, usage)
return &p
}
// Float32SliceP is like Float32Slice, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Float32SliceP(name, shorthand string, value []float32, usage string) *[]float32 {
p := []float32{}
f.Float32SliceVarP(&p, name, shorthand, value, usage)
return &p
}
// Float32Slice defines a []float32 flag with specified name, default value, and usage string.
// The return value is the address of a []float32 variable that stores the value of the flag.
func Float32Slice(name string, value []float32, usage string) *[]float32 {
return CommandLine.Float32SliceP(name, "", value, usage)
}
// Float32SliceP is like Float32Slice, but accepts a shorthand letter that can be used after a single dash.
func Float32SliceP(name, shorthand string, value []float32, usage string) *[]float32 {
return CommandLine.Float32SliceP(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/string_to_string.go | vendor/github.com/spf13/pflag/string_to_string.go | package pflag
import (
"bytes"
"encoding/csv"
"fmt"
"strings"
)
// -- stringToString Value
type stringToStringValue struct {
value *map[string]string
changed bool
}
func newStringToStringValue(val map[string]string, p *map[string]string) *stringToStringValue {
ssv := new(stringToStringValue)
ssv.value = p
*ssv.value = val
return ssv
}
// Format: a=1,b=2
func (s *stringToStringValue) Set(val string) error {
var ss []string
n := strings.Count(val, "=")
switch n {
case 0:
return fmt.Errorf("%s must be formatted as key=value", val)
case 1:
ss = append(ss, strings.Trim(val, `"`))
default:
r := csv.NewReader(strings.NewReader(val))
var err error
ss, err = r.Read()
if err != nil {
return err
}
}
out := make(map[string]string, len(ss))
for _, pair := range ss {
kv := strings.SplitN(pair, "=", 2)
if len(kv) != 2 {
return fmt.Errorf("%s must be formatted as key=value", pair)
}
out[kv[0]] = kv[1]
}
if !s.changed {
*s.value = out
} else {
for k, v := range out {
(*s.value)[k] = v
}
}
s.changed = true
return nil
}
func (s *stringToStringValue) Type() string {
return "stringToString"
}
func (s *stringToStringValue) String() string {
records := make([]string, 0, len(*s.value)>>1)
for k, v := range *s.value {
records = append(records, k+"="+v)
}
var buf bytes.Buffer
w := csv.NewWriter(&buf)
if err := w.Write(records); err != nil {
panic(err)
}
w.Flush()
return "[" + strings.TrimSpace(buf.String()) + "]"
}
func stringToStringConv(val string) (interface{}, error) {
val = strings.Trim(val, "[]")
// An empty string would cause an empty map
if len(val) == 0 {
return map[string]string{}, nil
}
r := csv.NewReader(strings.NewReader(val))
ss, err := r.Read()
if err != nil {
return nil, err
}
out := make(map[string]string, len(ss))
for _, pair := range ss {
kv := strings.SplitN(pair, "=", 2)
if len(kv) != 2 {
return nil, fmt.Errorf("%s must be formatted as key=value", pair)
}
out[kv[0]] = kv[1]
}
return out, nil
}
// GetStringToString return the map[string]string value of a flag with the given name
func (f *FlagSet) GetStringToString(name string) (map[string]string, error) {
val, err := f.getFlagType(name, "stringToString", stringToStringConv)
if err != nil {
return map[string]string{}, err
}
return val.(map[string]string), nil
}
// StringToStringVar defines a string flag with specified name, default value, and usage string.
// The argument p points to a map[string]string variable in which to store the values of the multiple flags.
// The value of each argument will not try to be separated by comma
func (f *FlagSet) StringToStringVar(p *map[string]string, name string, value map[string]string, usage string) {
f.VarP(newStringToStringValue(value, p), name, "", usage)
}
// StringToStringVarP is like StringToStringVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) StringToStringVarP(p *map[string]string, name, shorthand string, value map[string]string, usage string) {
f.VarP(newStringToStringValue(value, p), name, shorthand, usage)
}
// StringToStringVar defines a string flag with specified name, default value, and usage string.
// The argument p points to a map[string]string variable in which to store the value of the flag.
// The value of each argument will not try to be separated by comma
func StringToStringVar(p *map[string]string, name string, value map[string]string, usage string) {
CommandLine.VarP(newStringToStringValue(value, p), name, "", usage)
}
// StringToStringVarP is like StringToStringVar, but accepts a shorthand letter that can be used after a single dash.
func StringToStringVarP(p *map[string]string, name, shorthand string, value map[string]string, usage string) {
CommandLine.VarP(newStringToStringValue(value, p), name, shorthand, usage)
}
// StringToString defines a string flag with specified name, default value, and usage string.
// The return value is the address of a map[string]string variable that stores the value of the flag.
// The value of each argument will not try to be separated by comma
func (f *FlagSet) StringToString(name string, value map[string]string, usage string) *map[string]string {
p := map[string]string{}
f.StringToStringVarP(&p, name, "", value, usage)
return &p
}
// StringToStringP is like StringToString, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) StringToStringP(name, shorthand string, value map[string]string, usage string) *map[string]string {
p := map[string]string{}
f.StringToStringVarP(&p, name, shorthand, value, usage)
return &p
}
// StringToString defines a string flag with specified name, default value, and usage string.
// The return value is the address of a map[string]string variable that stores the value of the flag.
// The value of each argument will not try to be separated by comma
func StringToString(name string, value map[string]string, usage string) *map[string]string {
return CommandLine.StringToStringP(name, "", value, usage)
}
// StringToStringP is like StringToString, but accepts a shorthand letter that can be used after a single dash.
func StringToStringP(name, shorthand string, value map[string]string, usage string) *map[string]string {
return CommandLine.StringToStringP(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/duration.go | vendor/github.com/spf13/pflag/duration.go | package pflag
import (
"time"
)
// -- time.Duration Value
type durationValue time.Duration
func newDurationValue(val time.Duration, p *time.Duration) *durationValue {
*p = val
return (*durationValue)(p)
}
func (d *durationValue) Set(s string) error {
v, err := time.ParseDuration(s)
*d = durationValue(v)
return err
}
func (d *durationValue) Type() string {
return "duration"
}
func (d *durationValue) String() string { return (*time.Duration)(d).String() }
func durationConv(sval string) (interface{}, error) {
return time.ParseDuration(sval)
}
// GetDuration return the duration value of a flag with the given name
func (f *FlagSet) GetDuration(name string) (time.Duration, error) {
val, err := f.getFlagType(name, "duration", durationConv)
if err != nil {
return 0, err
}
return val.(time.Duration), nil
}
// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
// The argument p points to a time.Duration variable in which to store the value of the flag.
func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
f.VarP(newDurationValue(value, p), name, "", usage)
}
// DurationVarP is like DurationVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) {
f.VarP(newDurationValue(value, p), name, shorthand, usage)
}
// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
// The argument p points to a time.Duration variable in which to store the value of the flag.
func DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
CommandLine.VarP(newDurationValue(value, p), name, "", usage)
}
// DurationVarP is like DurationVar, but accepts a shorthand letter that can be used after a single dash.
func DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) {
CommandLine.VarP(newDurationValue(value, p), name, shorthand, usage)
}
// Duration defines a time.Duration flag with specified name, default value, and usage string.
// The return value is the address of a time.Duration variable that stores the value of the flag.
func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration {
p := new(time.Duration)
f.DurationVarP(p, name, "", value, usage)
return p
}
// DurationP is like Duration, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration {
p := new(time.Duration)
f.DurationVarP(p, name, shorthand, value, usage)
return p
}
// Duration defines a time.Duration flag with specified name, default value, and usage string.
// The return value is the address of a time.Duration variable that stores the value of the flag.
func Duration(name string, value time.Duration, usage string) *time.Duration {
return CommandLine.DurationP(name, "", value, usage)
}
// DurationP is like Duration, but accepts a shorthand letter that can be used after a single dash.
func DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration {
return CommandLine.DurationP(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/count.go | vendor/github.com/spf13/pflag/count.go | package pflag
import "strconv"
// -- count Value
type countValue int
func newCountValue(val int, p *int) *countValue {
*p = val
return (*countValue)(p)
}
func (i *countValue) Set(s string) error {
// "+1" means that no specific value was passed, so increment
if s == "+1" {
*i = countValue(*i + 1)
return nil
}
v, err := strconv.ParseInt(s, 0, 0)
*i = countValue(v)
return err
}
func (i *countValue) Type() string {
return "count"
}
func (i *countValue) String() string { return strconv.Itoa(int(*i)) }
func countConv(sval string) (interface{}, error) {
i, err := strconv.Atoi(sval)
if err != nil {
return nil, err
}
return i, nil
}
// GetCount return the int value of a flag with the given name
func (f *FlagSet) GetCount(name string) (int, error) {
val, err := f.getFlagType(name, "count", countConv)
if err != nil {
return 0, err
}
return val.(int), nil
}
// CountVar defines a count flag with specified name, default value, and usage string.
// The argument p points to an int variable in which to store the value of the flag.
// A count flag will add 1 to its value every time it is found on the command line
func (f *FlagSet) CountVar(p *int, name string, usage string) {
f.CountVarP(p, name, "", usage)
}
// CountVarP is like CountVar only take a shorthand for the flag name.
func (f *FlagSet) CountVarP(p *int, name, shorthand string, usage string) {
flag := f.VarPF(newCountValue(0, p), name, shorthand, usage)
flag.NoOptDefVal = "+1"
}
// CountVar like CountVar only the flag is placed on the CommandLine instead of a given flag set
func CountVar(p *int, name string, usage string) {
CommandLine.CountVar(p, name, usage)
}
// CountVarP is like CountVar only take a shorthand for the flag name.
func CountVarP(p *int, name, shorthand string, usage string) {
CommandLine.CountVarP(p, name, shorthand, usage)
}
// Count defines a count flag with specified name, default value, and usage string.
// The return value is the address of an int variable that stores the value of the flag.
// A count flag will add 1 to its value every time it is found on the command line
func (f *FlagSet) Count(name string, usage string) *int {
p := new(int)
f.CountVarP(p, name, "", usage)
return p
}
// CountP is like Count only takes a shorthand for the flag name.
func (f *FlagSet) CountP(name, shorthand string, usage string) *int {
p := new(int)
f.CountVarP(p, name, shorthand, usage)
return p
}
// Count defines a count flag with specified name, default value, and usage string.
// The return value is the address of an int variable that stores the value of the flag.
// A count flag will add 1 to its value evey time it is found on the command line
func Count(name string, usage string) *int {
return CommandLine.CountP(name, "", usage)
}
// CountP is like Count only takes a shorthand for the flag name.
func CountP(name, shorthand string, usage string) *int {
return CommandLine.CountP(name, shorthand, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/string_array.go | vendor/github.com/spf13/pflag/string_array.go | package pflag
// -- stringArray Value
type stringArrayValue struct {
value *[]string
changed bool
}
func newStringArrayValue(val []string, p *[]string) *stringArrayValue {
ssv := new(stringArrayValue)
ssv.value = p
*ssv.value = val
return ssv
}
func (s *stringArrayValue) Set(val string) error {
if !s.changed {
*s.value = []string{val}
s.changed = true
} else {
*s.value = append(*s.value, val)
}
return nil
}
func (s *stringArrayValue) Append(val string) error {
*s.value = append(*s.value, val)
return nil
}
func (s *stringArrayValue) Replace(val []string) error {
out := make([]string, len(val))
for i, d := range val {
var err error
out[i] = d
if err != nil {
return err
}
}
*s.value = out
return nil
}
func (s *stringArrayValue) GetSlice() []string {
out := make([]string, len(*s.value))
for i, d := range *s.value {
out[i] = d
}
return out
}
func (s *stringArrayValue) Type() string {
return "stringArray"
}
func (s *stringArrayValue) String() string {
str, _ := writeAsCSV(*s.value)
return "[" + str + "]"
}
func stringArrayConv(sval string) (interface{}, error) {
sval = sval[1 : len(sval)-1]
// An empty string would cause a array with one (empty) string
if len(sval) == 0 {
return []string{}, nil
}
return readAsCSV(sval)
}
// GetStringArray return the []string value of a flag with the given name
func (f *FlagSet) GetStringArray(name string) ([]string, error) {
val, err := f.getFlagType(name, "stringArray", stringArrayConv)
if err != nil {
return []string{}, err
}
return val.([]string), nil
}
// StringArrayVar defines a string flag with specified name, default value, and usage string.
// The argument p points to a []string variable in which to store the values of the multiple flags.
// The value of each argument will not try to be separated by comma. Use a StringSlice for that.
func (f *FlagSet) StringArrayVar(p *[]string, name string, value []string, usage string) {
f.VarP(newStringArrayValue(value, p), name, "", usage)
}
// StringArrayVarP is like StringArrayVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) StringArrayVarP(p *[]string, name, shorthand string, value []string, usage string) {
f.VarP(newStringArrayValue(value, p), name, shorthand, usage)
}
// StringArrayVar defines a string flag with specified name, default value, and usage string.
// The argument p points to a []string variable in which to store the value of the flag.
// The value of each argument will not try to be separated by comma. Use a StringSlice for that.
func StringArrayVar(p *[]string, name string, value []string, usage string) {
CommandLine.VarP(newStringArrayValue(value, p), name, "", usage)
}
// StringArrayVarP is like StringArrayVar, but accepts a shorthand letter that can be used after a single dash.
func StringArrayVarP(p *[]string, name, shorthand string, value []string, usage string) {
CommandLine.VarP(newStringArrayValue(value, p), name, shorthand, usage)
}
// StringArray defines a string flag with specified name, default value, and usage string.
// The return value is the address of a []string variable that stores the value of the flag.
// The value of each argument will not try to be separated by comma. Use a StringSlice for that.
func (f *FlagSet) StringArray(name string, value []string, usage string) *[]string {
p := []string{}
f.StringArrayVarP(&p, name, "", value, usage)
return &p
}
// StringArrayP is like StringArray, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) StringArrayP(name, shorthand string, value []string, usage string) *[]string {
p := []string{}
f.StringArrayVarP(&p, name, shorthand, value, usage)
return &p
}
// StringArray defines a string flag with specified name, default value, and usage string.
// The return value is the address of a []string variable that stores the value of the flag.
// The value of each argument will not try to be separated by comma. Use a StringSlice for that.
func StringArray(name string, value []string, usage string) *[]string {
return CommandLine.StringArrayP(name, "", value, usage)
}
// StringArrayP is like StringArray, but accepts a shorthand letter that can be used after a single dash.
func StringArrayP(name, shorthand string, value []string, usage string) *[]string {
return CommandLine.StringArrayP(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/float64_slice.go | vendor/github.com/spf13/pflag/float64_slice.go | package pflag
import (
"fmt"
"strconv"
"strings"
)
// -- float64Slice Value
type float64SliceValue struct {
value *[]float64
changed bool
}
func newFloat64SliceValue(val []float64, p *[]float64) *float64SliceValue {
isv := new(float64SliceValue)
isv.value = p
*isv.value = val
return isv
}
func (s *float64SliceValue) Set(val string) error {
ss := strings.Split(val, ",")
out := make([]float64, len(ss))
for i, d := range ss {
var err error
out[i], err = strconv.ParseFloat(d, 64)
if err != nil {
return err
}
}
if !s.changed {
*s.value = out
} else {
*s.value = append(*s.value, out...)
}
s.changed = true
return nil
}
func (s *float64SliceValue) Type() string {
return "float64Slice"
}
func (s *float64SliceValue) String() string {
out := make([]string, len(*s.value))
for i, d := range *s.value {
out[i] = fmt.Sprintf("%f", d)
}
return "[" + strings.Join(out, ",") + "]"
}
func (s *float64SliceValue) fromString(val string) (float64, error) {
return strconv.ParseFloat(val, 64)
}
func (s *float64SliceValue) toString(val float64) string {
return fmt.Sprintf("%f", val)
}
func (s *float64SliceValue) Append(val string) error {
i, err := s.fromString(val)
if err != nil {
return err
}
*s.value = append(*s.value, i)
return nil
}
func (s *float64SliceValue) Replace(val []string) error {
out := make([]float64, len(val))
for i, d := range val {
var err error
out[i], err = s.fromString(d)
if err != nil {
return err
}
}
*s.value = out
return nil
}
func (s *float64SliceValue) GetSlice() []string {
out := make([]string, len(*s.value))
for i, d := range *s.value {
out[i] = s.toString(d)
}
return out
}
func float64SliceConv(val string) (interface{}, error) {
val = strings.Trim(val, "[]")
// Empty string would cause a slice with one (empty) entry
if len(val) == 0 {
return []float64{}, nil
}
ss := strings.Split(val, ",")
out := make([]float64, len(ss))
for i, d := range ss {
var err error
out[i], err = strconv.ParseFloat(d, 64)
if err != nil {
return nil, err
}
}
return out, nil
}
// GetFloat64Slice return the []float64 value of a flag with the given name
func (f *FlagSet) GetFloat64Slice(name string) ([]float64, error) {
val, err := f.getFlagType(name, "float64Slice", float64SliceConv)
if err != nil {
return []float64{}, err
}
return val.([]float64), nil
}
// Float64SliceVar defines a float64Slice flag with specified name, default value, and usage string.
// The argument p points to a []float64 variable in which to store the value of the flag.
func (f *FlagSet) Float64SliceVar(p *[]float64, name string, value []float64, usage string) {
f.VarP(newFloat64SliceValue(value, p), name, "", usage)
}
// Float64SliceVarP is like Float64SliceVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Float64SliceVarP(p *[]float64, name, shorthand string, value []float64, usage string) {
f.VarP(newFloat64SliceValue(value, p), name, shorthand, usage)
}
// Float64SliceVar defines a float64[] flag with specified name, default value, and usage string.
// The argument p points to a float64[] variable in which to store the value of the flag.
func Float64SliceVar(p *[]float64, name string, value []float64, usage string) {
CommandLine.VarP(newFloat64SliceValue(value, p), name, "", usage)
}
// Float64SliceVarP is like Float64SliceVar, but accepts a shorthand letter that can be used after a single dash.
func Float64SliceVarP(p *[]float64, name, shorthand string, value []float64, usage string) {
CommandLine.VarP(newFloat64SliceValue(value, p), name, shorthand, usage)
}
// Float64Slice defines a []float64 flag with specified name, default value, and usage string.
// The return value is the address of a []float64 variable that stores the value of the flag.
func (f *FlagSet) Float64Slice(name string, value []float64, usage string) *[]float64 {
p := []float64{}
f.Float64SliceVarP(&p, name, "", value, usage)
return &p
}
// Float64SliceP is like Float64Slice, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Float64SliceP(name, shorthand string, value []float64, usage string) *[]float64 {
p := []float64{}
f.Float64SliceVarP(&p, name, shorthand, value, usage)
return &p
}
// Float64Slice defines a []float64 flag with specified name, default value, and usage string.
// The return value is the address of a []float64 variable that stores the value of the flag.
func Float64Slice(name string, value []float64, usage string) *[]float64 {
return CommandLine.Float64SliceP(name, "", value, usage)
}
// Float64SliceP is like Float64Slice, but accepts a shorthand letter that can be used after a single dash.
func Float64SliceP(name, shorthand string, value []float64, usage string) *[]float64 {
return CommandLine.Float64SliceP(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/uint_slice.go | vendor/github.com/spf13/pflag/uint_slice.go | package pflag
import (
"fmt"
"strconv"
"strings"
)
// -- uintSlice Value
type uintSliceValue struct {
value *[]uint
changed bool
}
func newUintSliceValue(val []uint, p *[]uint) *uintSliceValue {
uisv := new(uintSliceValue)
uisv.value = p
*uisv.value = val
return uisv
}
func (s *uintSliceValue) Set(val string) error {
ss := strings.Split(val, ",")
out := make([]uint, len(ss))
for i, d := range ss {
u, err := strconv.ParseUint(d, 10, 0)
if err != nil {
return err
}
out[i] = uint(u)
}
if !s.changed {
*s.value = out
} else {
*s.value = append(*s.value, out...)
}
s.changed = true
return nil
}
func (s *uintSliceValue) Type() string {
return "uintSlice"
}
func (s *uintSliceValue) String() string {
out := make([]string, len(*s.value))
for i, d := range *s.value {
out[i] = fmt.Sprintf("%d", d)
}
return "[" + strings.Join(out, ",") + "]"
}
func (s *uintSliceValue) fromString(val string) (uint, error) {
t, err := strconv.ParseUint(val, 10, 0)
if err != nil {
return 0, err
}
return uint(t), nil
}
func (s *uintSliceValue) toString(val uint) string {
return fmt.Sprintf("%d", val)
}
func (s *uintSliceValue) Append(val string) error {
i, err := s.fromString(val)
if err != nil {
return err
}
*s.value = append(*s.value, i)
return nil
}
func (s *uintSliceValue) Replace(val []string) error {
out := make([]uint, len(val))
for i, d := range val {
var err error
out[i], err = s.fromString(d)
if err != nil {
return err
}
}
*s.value = out
return nil
}
func (s *uintSliceValue) GetSlice() []string {
out := make([]string, len(*s.value))
for i, d := range *s.value {
out[i] = s.toString(d)
}
return out
}
func uintSliceConv(val string) (interface{}, error) {
val = strings.Trim(val, "[]")
// Empty string would cause a slice with one (empty) entry
if len(val) == 0 {
return []uint{}, nil
}
ss := strings.Split(val, ",")
out := make([]uint, len(ss))
for i, d := range ss {
u, err := strconv.ParseUint(d, 10, 0)
if err != nil {
return nil, err
}
out[i] = uint(u)
}
return out, nil
}
// GetUintSlice returns the []uint value of a flag with the given name.
func (f *FlagSet) GetUintSlice(name string) ([]uint, error) {
val, err := f.getFlagType(name, "uintSlice", uintSliceConv)
if err != nil {
return []uint{}, err
}
return val.([]uint), nil
}
// UintSliceVar defines a uintSlice flag with specified name, default value, and usage string.
// The argument p points to a []uint variable in which to store the value of the flag.
func (f *FlagSet) UintSliceVar(p *[]uint, name string, value []uint, usage string) {
f.VarP(newUintSliceValue(value, p), name, "", usage)
}
// UintSliceVarP is like UintSliceVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) UintSliceVarP(p *[]uint, name, shorthand string, value []uint, usage string) {
f.VarP(newUintSliceValue(value, p), name, shorthand, usage)
}
// UintSliceVar defines a uint[] flag with specified name, default value, and usage string.
// The argument p points to a uint[] variable in which to store the value of the flag.
func UintSliceVar(p *[]uint, name string, value []uint, usage string) {
CommandLine.VarP(newUintSliceValue(value, p), name, "", usage)
}
// UintSliceVarP is like the UintSliceVar, but accepts a shorthand letter that can be used after a single dash.
func UintSliceVarP(p *[]uint, name, shorthand string, value []uint, usage string) {
CommandLine.VarP(newUintSliceValue(value, p), name, shorthand, usage)
}
// UintSlice defines a []uint flag with specified name, default value, and usage string.
// The return value is the address of a []uint variable that stores the value of the flag.
func (f *FlagSet) UintSlice(name string, value []uint, usage string) *[]uint {
p := []uint{}
f.UintSliceVarP(&p, name, "", value, usage)
return &p
}
// UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) UintSliceP(name, shorthand string, value []uint, usage string) *[]uint {
p := []uint{}
f.UintSliceVarP(&p, name, shorthand, value, usage)
return &p
}
// UintSlice defines a []uint flag with specified name, default value, and usage string.
// The return value is the address of a []uint variable that stores the value of the flag.
func UintSlice(name string, value []uint, usage string) *[]uint {
return CommandLine.UintSliceP(name, "", value, usage)
}
// UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash.
func UintSliceP(name, shorthand string, value []uint, usage string) *[]uint {
return CommandLine.UintSliceP(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/spf13/pflag/ip.go | vendor/github.com/spf13/pflag/ip.go | package pflag
import (
"fmt"
"net"
"strings"
)
// -- net.IP value
type ipValue net.IP
func newIPValue(val net.IP, p *net.IP) *ipValue {
*p = val
return (*ipValue)(p)
}
func (i *ipValue) String() string { return net.IP(*i).String() }
func (i *ipValue) Set(s string) error {
ip := net.ParseIP(strings.TrimSpace(s))
if ip == nil {
return fmt.Errorf("failed to parse IP: %q", s)
}
*i = ipValue(ip)
return nil
}
func (i *ipValue) Type() string {
return "ip"
}
func ipConv(sval string) (interface{}, error) {
ip := net.ParseIP(sval)
if ip != nil {
return ip, nil
}
return nil, fmt.Errorf("invalid string being converted to IP address: %s", sval)
}
// GetIP return the net.IP value of a flag with the given name
func (f *FlagSet) GetIP(name string) (net.IP, error) {
val, err := f.getFlagType(name, "ip", ipConv)
if err != nil {
return nil, err
}
return val.(net.IP), nil
}
// IPVar defines an net.IP flag with specified name, default value, and usage string.
// The argument p points to an net.IP variable in which to store the value of the flag.
func (f *FlagSet) IPVar(p *net.IP, name string, value net.IP, usage string) {
f.VarP(newIPValue(value, p), name, "", usage)
}
// IPVarP is like IPVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) IPVarP(p *net.IP, name, shorthand string, value net.IP, usage string) {
f.VarP(newIPValue(value, p), name, shorthand, usage)
}
// IPVar defines an net.IP flag with specified name, default value, and usage string.
// The argument p points to an net.IP variable in which to store the value of the flag.
func IPVar(p *net.IP, name string, value net.IP, usage string) {
CommandLine.VarP(newIPValue(value, p), name, "", usage)
}
// IPVarP is like IPVar, but accepts a shorthand letter that can be used after a single dash.
func IPVarP(p *net.IP, name, shorthand string, value net.IP, usage string) {
CommandLine.VarP(newIPValue(value, p), name, shorthand, usage)
}
// IP defines an net.IP flag with specified name, default value, and usage string.
// The return value is the address of an net.IP variable that stores the value of the flag.
func (f *FlagSet) IP(name string, value net.IP, usage string) *net.IP {
p := new(net.IP)
f.IPVarP(p, name, "", value, usage)
return p
}
// IPP is like IP, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) IPP(name, shorthand string, value net.IP, usage string) *net.IP {
p := new(net.IP)
f.IPVarP(p, name, shorthand, value, usage)
return p
}
// IP defines an net.IP flag with specified name, default value, and usage string.
// The return value is the address of an net.IP variable that stores the value of the flag.
func IP(name string, value net.IP, usage string) *net.IP {
return CommandLine.IPP(name, "", value, usage)
}
// IPP is like IP, but accepts a shorthand letter that can be used after a single dash.
func IPP(name, shorthand string, value net.IP, usage string) *net.IP {
return CommandLine.IPP(name, shorthand, value, usage)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/blang/semver/v4/json.go | vendor/github.com/blang/semver/v4/json.go | package semver
import (
"encoding/json"
)
// MarshalJSON implements the encoding/json.Marshaler interface.
func (v Version) MarshalJSON() ([]byte, error) {
return json.Marshal(v.String())
}
// UnmarshalJSON implements the encoding/json.Unmarshaler interface.
func (v *Version) UnmarshalJSON(data []byte) (err error) {
var versionString string
if err = json.Unmarshal(data, &versionString); err != nil {
return
}
*v, err = Parse(versionString)
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/blang/semver/v4/sort.go | vendor/github.com/blang/semver/v4/sort.go | package semver
import (
"sort"
)
// Versions represents multiple versions.
type Versions []Version
// Len returns length of version collection
func (s Versions) Len() int {
return len(s)
}
// Swap swaps two versions inside the collection by its indices
func (s Versions) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
// Less checks if version at index i is less than version at index j
func (s Versions) Less(i, j int) bool {
return s[i].LT(s[j])
}
// Sort sorts a slice of versions
func Sort(versions []Version) {
sort.Sort(Versions(versions))
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/blang/semver/v4/sql.go | vendor/github.com/blang/semver/v4/sql.go | package semver
import (
"database/sql/driver"
"fmt"
)
// Scan implements the database/sql.Scanner interface.
func (v *Version) Scan(src interface{}) (err error) {
var str string
switch src := src.(type) {
case string:
str = src
case []byte:
str = string(src)
default:
return fmt.Errorf("version.Scan: cannot convert %T to string", src)
}
if t, err := Parse(str); err == nil {
*v = t
}
return
}
// Value implements the database/sql/driver.Valuer interface.
func (v Version) Value() (driver.Value, error) {
return v.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/blang/semver/v4/range.go | vendor/github.com/blang/semver/v4/range.go | package semver
import (
"fmt"
"strconv"
"strings"
"unicode"
)
type wildcardType int
const (
noneWildcard wildcardType = iota
majorWildcard wildcardType = 1
minorWildcard wildcardType = 2
patchWildcard wildcardType = 3
)
func wildcardTypefromInt(i int) wildcardType {
switch i {
case 1:
return majorWildcard
case 2:
return minorWildcard
case 3:
return patchWildcard
default:
return noneWildcard
}
}
type comparator func(Version, Version) bool
var (
compEQ comparator = func(v1 Version, v2 Version) bool {
return v1.Compare(v2) == 0
}
compNE = func(v1 Version, v2 Version) bool {
return v1.Compare(v2) != 0
}
compGT = func(v1 Version, v2 Version) bool {
return v1.Compare(v2) == 1
}
compGE = func(v1 Version, v2 Version) bool {
return v1.Compare(v2) >= 0
}
compLT = func(v1 Version, v2 Version) bool {
return v1.Compare(v2) == -1
}
compLE = func(v1 Version, v2 Version) bool {
return v1.Compare(v2) <= 0
}
)
type versionRange struct {
v Version
c comparator
}
// rangeFunc creates a Range from the given versionRange.
func (vr *versionRange) rangeFunc() Range {
return Range(func(v Version) bool {
return vr.c(v, vr.v)
})
}
// Range represents a range of versions.
// A Range can be used to check if a Version satisfies it:
//
// range, err := semver.ParseRange(">1.0.0 <2.0.0")
// range(semver.MustParse("1.1.1") // returns true
type Range func(Version) bool
// OR combines the existing Range with another Range using logical OR.
func (rf Range) OR(f Range) Range {
return Range(func(v Version) bool {
return rf(v) || f(v)
})
}
// AND combines the existing Range with another Range using logical AND.
func (rf Range) AND(f Range) Range {
return Range(func(v Version) bool {
return rf(v) && f(v)
})
}
// ParseRange parses a range and returns a Range.
// If the range could not be parsed an error is returned.
//
// Valid ranges are:
// - "<1.0.0"
// - "<=1.0.0"
// - ">1.0.0"
// - ">=1.0.0"
// - "1.0.0", "=1.0.0", "==1.0.0"
// - "!1.0.0", "!=1.0.0"
//
// A Range can consist of multiple ranges separated by space:
// Ranges can be linked by logical AND:
// - ">1.0.0 <2.0.0" would match between both ranges, so "1.1.1" and "1.8.7" but not "1.0.0" or "2.0.0"
// - ">1.0.0 <3.0.0 !2.0.3-beta.2" would match every version between 1.0.0 and 3.0.0 except 2.0.3-beta.2
//
// Ranges can also be linked by logical OR:
// - "<2.0.0 || >=3.0.0" would match "1.x.x" and "3.x.x" but not "2.x.x"
//
// AND has a higher precedence than OR. It's not possible to use brackets.
//
// Ranges can be combined by both AND and OR
//
// - `>1.0.0 <2.0.0 || >3.0.0 !4.2.1` would match `1.2.3`, `1.9.9`, `3.1.1`, but not `4.2.1`, `2.1.1`
func ParseRange(s string) (Range, error) {
parts := splitAndTrim(s)
orParts, err := splitORParts(parts)
if err != nil {
return nil, err
}
expandedParts, err := expandWildcardVersion(orParts)
if err != nil {
return nil, err
}
var orFn Range
for _, p := range expandedParts {
var andFn Range
for _, ap := range p {
opStr, vStr, err := splitComparatorVersion(ap)
if err != nil {
return nil, err
}
vr, err := buildVersionRange(opStr, vStr)
if err != nil {
return nil, fmt.Errorf("Could not parse Range %q: %s", ap, err)
}
rf := vr.rangeFunc()
// Set function
if andFn == nil {
andFn = rf
} else { // Combine with existing function
andFn = andFn.AND(rf)
}
}
if orFn == nil {
orFn = andFn
} else {
orFn = orFn.OR(andFn)
}
}
return orFn, nil
}
// splitORParts splits the already cleaned parts by '||'.
// Checks for invalid positions of the operator and returns an
// error if found.
func splitORParts(parts []string) ([][]string, error) {
var ORparts [][]string
last := 0
for i, p := range parts {
if p == "||" {
if i == 0 {
return nil, fmt.Errorf("First element in range is '||'")
}
ORparts = append(ORparts, parts[last:i])
last = i + 1
}
}
if last == len(parts) {
return nil, fmt.Errorf("Last element in range is '||'")
}
ORparts = append(ORparts, parts[last:])
return ORparts, nil
}
// buildVersionRange takes a slice of 2: operator and version
// and builds a versionRange, otherwise an error.
func buildVersionRange(opStr, vStr string) (*versionRange, error) {
c := parseComparator(opStr)
if c == nil {
return nil, fmt.Errorf("Could not parse comparator %q in %q", opStr, strings.Join([]string{opStr, vStr}, ""))
}
v, err := Parse(vStr)
if err != nil {
return nil, fmt.Errorf("Could not parse version %q in %q: %s", vStr, strings.Join([]string{opStr, vStr}, ""), err)
}
return &versionRange{
v: v,
c: c,
}, nil
}
// inArray checks if a byte is contained in an array of bytes
func inArray(s byte, list []byte) bool {
for _, el := range list {
if el == s {
return true
}
}
return false
}
// splitAndTrim splits a range string by spaces and cleans whitespaces
func splitAndTrim(s string) (result []string) {
last := 0
var lastChar byte
excludeFromSplit := []byte{'>', '<', '='}
for i := 0; i < len(s); i++ {
if s[i] == ' ' && !inArray(lastChar, excludeFromSplit) {
if last < i-1 {
result = append(result, s[last:i])
}
last = i + 1
} else if s[i] != ' ' {
lastChar = s[i]
}
}
if last < len(s)-1 {
result = append(result, s[last:])
}
for i, v := range result {
result[i] = strings.Replace(v, " ", "", -1)
}
// parts := strings.Split(s, " ")
// for _, x := range parts {
// if s := strings.TrimSpace(x); len(s) != 0 {
// result = append(result, s)
// }
// }
return
}
// splitComparatorVersion splits the comparator from the version.
// Input must be free of leading or trailing spaces.
func splitComparatorVersion(s string) (string, string, error) {
i := strings.IndexFunc(s, unicode.IsDigit)
if i == -1 {
return "", "", fmt.Errorf("Could not get version from string: %q", s)
}
return strings.TrimSpace(s[0:i]), s[i:], nil
}
// getWildcardType will return the type of wildcard that the
// passed version contains
func getWildcardType(vStr string) wildcardType {
parts := strings.Split(vStr, ".")
nparts := len(parts)
wildcard := parts[nparts-1]
possibleWildcardType := wildcardTypefromInt(nparts)
if wildcard == "x" {
return possibleWildcardType
}
return noneWildcard
}
// createVersionFromWildcard will convert a wildcard version
// into a regular version, replacing 'x's with '0's, handling
// special cases like '1.x.x' and '1.x'
func createVersionFromWildcard(vStr string) string {
// handle 1.x.x
vStr2 := strings.Replace(vStr, ".x.x", ".x", 1)
vStr2 = strings.Replace(vStr2, ".x", ".0", 1)
parts := strings.Split(vStr2, ".")
// handle 1.x
if len(parts) == 2 {
return vStr2 + ".0"
}
return vStr2
}
// incrementMajorVersion will increment the major version
// of the passed version
func incrementMajorVersion(vStr string) (string, error) {
parts := strings.Split(vStr, ".")
i, err := strconv.Atoi(parts[0])
if err != nil {
return "", err
}
parts[0] = strconv.Itoa(i + 1)
return strings.Join(parts, "."), nil
}
// incrementMajorVersion will increment the minor version
// of the passed version
func incrementMinorVersion(vStr string) (string, error) {
parts := strings.Split(vStr, ".")
i, err := strconv.Atoi(parts[1])
if err != nil {
return "", err
}
parts[1] = strconv.Itoa(i + 1)
return strings.Join(parts, "."), nil
}
// expandWildcardVersion will expand wildcards inside versions
// following these rules:
//
// * when dealing with patch wildcards:
// >= 1.2.x will become >= 1.2.0
// <= 1.2.x will become < 1.3.0
// > 1.2.x will become >= 1.3.0
// < 1.2.x will become < 1.2.0
// != 1.2.x will become < 1.2.0 >= 1.3.0
//
// * when dealing with minor wildcards:
// >= 1.x will become >= 1.0.0
// <= 1.x will become < 2.0.0
// > 1.x will become >= 2.0.0
// < 1.0 will become < 1.0.0
// != 1.x will become < 1.0.0 >= 2.0.0
//
// * when dealing with wildcards without
// version operator:
// 1.2.x will become >= 1.2.0 < 1.3.0
// 1.x will become >= 1.0.0 < 2.0.0
func expandWildcardVersion(parts [][]string) ([][]string, error) {
var expandedParts [][]string
for _, p := range parts {
var newParts []string
for _, ap := range p {
if strings.Contains(ap, "x") {
opStr, vStr, err := splitComparatorVersion(ap)
if err != nil {
return nil, err
}
versionWildcardType := getWildcardType(vStr)
flatVersion := createVersionFromWildcard(vStr)
var resultOperator string
var shouldIncrementVersion bool
switch opStr {
case ">":
resultOperator = ">="
shouldIncrementVersion = true
case ">=":
resultOperator = ">="
case "<":
resultOperator = "<"
case "<=":
resultOperator = "<"
shouldIncrementVersion = true
case "", "=", "==":
newParts = append(newParts, ">="+flatVersion)
resultOperator = "<"
shouldIncrementVersion = true
case "!=", "!":
newParts = append(newParts, "<"+flatVersion)
resultOperator = ">="
shouldIncrementVersion = true
}
var resultVersion string
if shouldIncrementVersion {
switch versionWildcardType {
case patchWildcard:
resultVersion, _ = incrementMinorVersion(flatVersion)
case minorWildcard:
resultVersion, _ = incrementMajorVersion(flatVersion)
}
} else {
resultVersion = flatVersion
}
ap = resultOperator + resultVersion
}
newParts = append(newParts, ap)
}
expandedParts = append(expandedParts, newParts)
}
return expandedParts, nil
}
func parseComparator(s string) comparator {
switch s {
case "==":
fallthrough
case "":
fallthrough
case "=":
return compEQ
case ">":
return compGT
case ">=":
return compGE
case "<":
return compLT
case "<=":
return compLE
case "!":
fallthrough
case "!=":
return compNE
}
return nil
}
// MustParseRange is like ParseRange but panics if the range cannot be parsed.
func MustParseRange(s string) Range {
r, err := ParseRange(s)
if err != nil {
panic(`semver: ParseRange(` + s + `): ` + err.Error())
}
return 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/blang/semver/v4/semver.go | vendor/github.com/blang/semver/v4/semver.go | package semver
import (
"errors"
"fmt"
"strconv"
"strings"
)
const (
numbers string = "0123456789"
alphas = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-"
alphanum = alphas + numbers
)
// SpecVersion is the latest fully supported spec version of semver
var SpecVersion = Version{
Major: 2,
Minor: 0,
Patch: 0,
}
// Version represents a semver compatible version
type Version struct {
Major uint64
Minor uint64
Patch uint64
Pre []PRVersion
Build []string //No Precedence
}
// Version to string
func (v Version) String() string {
b := make([]byte, 0, 5)
b = strconv.AppendUint(b, v.Major, 10)
b = append(b, '.')
b = strconv.AppendUint(b, v.Minor, 10)
b = append(b, '.')
b = strconv.AppendUint(b, v.Patch, 10)
if len(v.Pre) > 0 {
b = append(b, '-')
b = append(b, v.Pre[0].String()...)
for _, pre := range v.Pre[1:] {
b = append(b, '.')
b = append(b, pre.String()...)
}
}
if len(v.Build) > 0 {
b = append(b, '+')
b = append(b, v.Build[0]...)
for _, build := range v.Build[1:] {
b = append(b, '.')
b = append(b, build...)
}
}
return string(b)
}
// FinalizeVersion discards prerelease and build number and only returns
// major, minor and patch number.
func (v Version) FinalizeVersion() string {
b := make([]byte, 0, 5)
b = strconv.AppendUint(b, v.Major, 10)
b = append(b, '.')
b = strconv.AppendUint(b, v.Minor, 10)
b = append(b, '.')
b = strconv.AppendUint(b, v.Patch, 10)
return string(b)
}
// Equals checks if v is equal to o.
func (v Version) Equals(o Version) bool {
return (v.Compare(o) == 0)
}
// EQ checks if v is equal to o.
func (v Version) EQ(o Version) bool {
return (v.Compare(o) == 0)
}
// NE checks if v is not equal to o.
func (v Version) NE(o Version) bool {
return (v.Compare(o) != 0)
}
// GT checks if v is greater than o.
func (v Version) GT(o Version) bool {
return (v.Compare(o) == 1)
}
// GTE checks if v is greater than or equal to o.
func (v Version) GTE(o Version) bool {
return (v.Compare(o) >= 0)
}
// GE checks if v is greater than or equal to o.
func (v Version) GE(o Version) bool {
return (v.Compare(o) >= 0)
}
// LT checks if v is less than o.
func (v Version) LT(o Version) bool {
return (v.Compare(o) == -1)
}
// LTE checks if v is less than or equal to o.
func (v Version) LTE(o Version) bool {
return (v.Compare(o) <= 0)
}
// LE checks if v is less than or equal to o.
func (v Version) LE(o Version) bool {
return (v.Compare(o) <= 0)
}
// Compare compares Versions v to o:
// -1 == v is less than o
// 0 == v is equal to o
// 1 == v is greater than o
func (v Version) Compare(o Version) int {
if v.Major != o.Major {
if v.Major > o.Major {
return 1
}
return -1
}
if v.Minor != o.Minor {
if v.Minor > o.Minor {
return 1
}
return -1
}
if v.Patch != o.Patch {
if v.Patch > o.Patch {
return 1
}
return -1
}
// Quick comparison if a version has no prerelease versions
if len(v.Pre) == 0 && len(o.Pre) == 0 {
return 0
} else if len(v.Pre) == 0 && len(o.Pre) > 0 {
return 1
} else if len(v.Pre) > 0 && len(o.Pre) == 0 {
return -1
}
i := 0
for ; i < len(v.Pre) && i < len(o.Pre); i++ {
if comp := v.Pre[i].Compare(o.Pre[i]); comp == 0 {
continue
} else if comp == 1 {
return 1
} else {
return -1
}
}
// If all pr versions are the equal but one has further prversion, this one greater
if i == len(v.Pre) && i == len(o.Pre) {
return 0
} else if i == len(v.Pre) && i < len(o.Pre) {
return -1
} else {
return 1
}
}
// IncrementPatch increments the patch version
func (v *Version) IncrementPatch() error {
v.Patch++
return nil
}
// IncrementMinor increments the minor version
func (v *Version) IncrementMinor() error {
v.Minor++
v.Patch = 0
return nil
}
// IncrementMajor increments the major version
func (v *Version) IncrementMajor() error {
v.Major++
v.Minor = 0
v.Patch = 0
return nil
}
// Validate validates v and returns error in case
func (v Version) Validate() error {
// Major, Minor, Patch already validated using uint64
for _, pre := range v.Pre {
if !pre.IsNum { //Numeric prerelease versions already uint64
if len(pre.VersionStr) == 0 {
return fmt.Errorf("Prerelease can not be empty %q", pre.VersionStr)
}
if !containsOnly(pre.VersionStr, alphanum) {
return fmt.Errorf("Invalid character(s) found in prerelease %q", pre.VersionStr)
}
}
}
for _, build := range v.Build {
if len(build) == 0 {
return fmt.Errorf("Build meta data can not be empty %q", build)
}
if !containsOnly(build, alphanum) {
return fmt.Errorf("Invalid character(s) found in build meta data %q", build)
}
}
return nil
}
// New is an alias for Parse and returns a pointer, parses version string and returns a validated Version or error
func New(s string) (*Version, error) {
v, err := Parse(s)
vp := &v
return vp, err
}
// Make is an alias for Parse, parses version string and returns a validated Version or error
func Make(s string) (Version, error) {
return Parse(s)
}
// ParseTolerant allows for certain version specifications that do not strictly adhere to semver
// specs to be parsed by this library. It does so by normalizing versions before passing them to
// Parse(). It currently trims spaces, removes a "v" prefix, adds a 0 patch number to versions
// with only major and minor components specified, and removes leading 0s.
func ParseTolerant(s string) (Version, error) {
s = strings.TrimSpace(s)
s = strings.TrimPrefix(s, "v")
// Split into major.minor.(patch+pr+meta)
parts := strings.SplitN(s, ".", 3)
// Remove leading zeros.
for i, p := range parts {
if len(p) > 1 {
p = strings.TrimLeft(p, "0")
if len(p) == 0 || !strings.ContainsAny(p[0:1], "0123456789") {
p = "0" + p
}
parts[i] = p
}
}
// Fill up shortened versions.
if len(parts) < 3 {
if strings.ContainsAny(parts[len(parts)-1], "+-") {
return Version{}, errors.New("Short version cannot contain PreRelease/Build meta data")
}
for len(parts) < 3 {
parts = append(parts, "0")
}
}
s = strings.Join(parts, ".")
return Parse(s)
}
// Parse parses version string and returns a validated Version or error
func Parse(s string) (Version, error) {
if len(s) == 0 {
return Version{}, errors.New("Version string empty")
}
// Split into major.minor.(patch+pr+meta)
parts := strings.SplitN(s, ".", 3)
if len(parts) != 3 {
return Version{}, errors.New("No Major.Minor.Patch elements found")
}
// Major
if !containsOnly(parts[0], numbers) {
return Version{}, fmt.Errorf("Invalid character(s) found in major number %q", parts[0])
}
if hasLeadingZeroes(parts[0]) {
return Version{}, fmt.Errorf("Major number must not contain leading zeroes %q", parts[0])
}
major, err := strconv.ParseUint(parts[0], 10, 64)
if err != nil {
return Version{}, err
}
// Minor
if !containsOnly(parts[1], numbers) {
return Version{}, fmt.Errorf("Invalid character(s) found in minor number %q", parts[1])
}
if hasLeadingZeroes(parts[1]) {
return Version{}, fmt.Errorf("Minor number must not contain leading zeroes %q", parts[1])
}
minor, err := strconv.ParseUint(parts[1], 10, 64)
if err != nil {
return Version{}, err
}
v := Version{}
v.Major = major
v.Minor = minor
var build, prerelease []string
patchStr := parts[2]
if buildIndex := strings.IndexRune(patchStr, '+'); buildIndex != -1 {
build = strings.Split(patchStr[buildIndex+1:], ".")
patchStr = patchStr[:buildIndex]
}
if preIndex := strings.IndexRune(patchStr, '-'); preIndex != -1 {
prerelease = strings.Split(patchStr[preIndex+1:], ".")
patchStr = patchStr[:preIndex]
}
if !containsOnly(patchStr, numbers) {
return Version{}, fmt.Errorf("Invalid character(s) found in patch number %q", patchStr)
}
if hasLeadingZeroes(patchStr) {
return Version{}, fmt.Errorf("Patch number must not contain leading zeroes %q", patchStr)
}
patch, err := strconv.ParseUint(patchStr, 10, 64)
if err != nil {
return Version{}, err
}
v.Patch = patch
// Prerelease
for _, prstr := range prerelease {
parsedPR, err := NewPRVersion(prstr)
if err != nil {
return Version{}, err
}
v.Pre = append(v.Pre, parsedPR)
}
// Build meta data
for _, str := range build {
if len(str) == 0 {
return Version{}, errors.New("Build meta data is empty")
}
if !containsOnly(str, alphanum) {
return Version{}, fmt.Errorf("Invalid character(s) found in build meta data %q", str)
}
v.Build = append(v.Build, str)
}
return v, nil
}
// MustParse is like Parse but panics if the version cannot be parsed.
func MustParse(s string) Version {
v, err := Parse(s)
if err != nil {
panic(`semver: Parse(` + s + `): ` + err.Error())
}
return v
}
// PRVersion represents a PreRelease Version
type PRVersion struct {
VersionStr string
VersionNum uint64
IsNum bool
}
// NewPRVersion creates a new valid prerelease version
func NewPRVersion(s string) (PRVersion, error) {
if len(s) == 0 {
return PRVersion{}, errors.New("Prerelease is empty")
}
v := PRVersion{}
if containsOnly(s, numbers) {
if hasLeadingZeroes(s) {
return PRVersion{}, fmt.Errorf("Numeric PreRelease version must not contain leading zeroes %q", s)
}
num, err := strconv.ParseUint(s, 10, 64)
// Might never be hit, but just in case
if err != nil {
return PRVersion{}, err
}
v.VersionNum = num
v.IsNum = true
} else if containsOnly(s, alphanum) {
v.VersionStr = s
v.IsNum = false
} else {
return PRVersion{}, fmt.Errorf("Invalid character(s) found in prerelease %q", s)
}
return v, nil
}
// IsNumeric checks if prerelease-version is numeric
func (v PRVersion) IsNumeric() bool {
return v.IsNum
}
// Compare compares two PreRelease Versions v and o:
// -1 == v is less than o
// 0 == v is equal to o
// 1 == v is greater than o
func (v PRVersion) Compare(o PRVersion) int {
if v.IsNum && !o.IsNum {
return -1
} else if !v.IsNum && o.IsNum {
return 1
} else if v.IsNum && o.IsNum {
if v.VersionNum == o.VersionNum {
return 0
} else if v.VersionNum > o.VersionNum {
return 1
} else {
return -1
}
} else { // both are Alphas
if v.VersionStr == o.VersionStr {
return 0
} else if v.VersionStr > o.VersionStr {
return 1
} else {
return -1
}
}
}
// PreRelease version to string
func (v PRVersion) String() string {
if v.IsNum {
return strconv.FormatUint(v.VersionNum, 10)
}
return v.VersionStr
}
func containsOnly(s string, set string) bool {
return strings.IndexFunc(s, func(r rune) bool {
return !strings.ContainsRune(set, r)
}) == -1
}
func hasLeadingZeroes(s string) bool {
return len(s) > 1 && s[0] == '0'
}
// NewBuildVersion creates a new valid build version
func NewBuildVersion(s string) (string, error) {
if len(s) == 0 {
return "", errors.New("Buildversion is empty")
}
if !containsOnly(s, alphanum) {
return "", fmt.Errorf("Invalid character(s) found in build meta data %q", s)
}
return s, nil
}
// FinalizeVersion returns the major, minor and patch number only and discards
// prerelease and build number.
func FinalizeVersion(s string) (string, error) {
v, err := Parse(s)
if err != nil {
return "", err
}
v.Pre = nil
v.Build = nil
finalVer := v.String()
return finalVer, 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/ugorji/go/codec/json.go | vendor/github.com/ugorji/go/codec/json.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
package codec
// By default, this json support uses base64 encoding for bytes, because you cannot
// store and read any arbitrary string in json (only unicode).
// However, the user can configre how to encode/decode bytes.
//
// This library specifically supports UTF-8 for encoding and decoding only.
//
// Note that the library will happily encode/decode things which are not valid
// json e.g. a map[int64]string. We do it for consistency. With valid json,
// we will encode and decode appropriately.
// Users can specify their map type if necessary to force it.
//
// We cannot use strconv.(Q|Unq)uote because json quotes/unquotes differently.
import (
"encoding/base64"
"math"
"reflect"
"strconv"
"time"
"unicode"
"unicode/utf16"
"unicode/utf8"
)
//--------------------------------
// jsonLits and jsonLitb are defined at the package level,
// so they are guaranteed to be stored efficiently, making
// for better append/string comparison/etc.
//
// (anecdotal evidence from some benchmarking on go 1.20 devel in 20220104)
const jsonLits = `"true"false"null"`
var jsonLitb = []byte(jsonLits)
const (
jsonLitT = 1
jsonLitF = 6
jsonLitN = 12
)
const jsonEncodeUintSmallsString = "" +
"00010203040506070809" +
"10111213141516171819" +
"20212223242526272829" +
"30313233343536373839" +
"40414243444546474849" +
"50515253545556575859" +
"60616263646566676869" +
"70717273747576777879" +
"80818283848586878889" +
"90919293949596979899"
var jsonEncodeUintSmallsStringBytes = []byte(jsonEncodeUintSmallsString)
const (
jsonU4Chk2 = '0'
jsonU4Chk1 = 'a' - 10
jsonU4Chk0 = 'A' - 10
)
const (
// If !jsonValidateSymbols, decoding will be faster, by skipping some checks:
// - If we see first character of null, false or true,
// do not validate subsequent characters.
// - e.g. if we see a n, assume null and skip next 3 characters,
// and do not validate they are ull.
// P.S. Do not expect a significant decoding boost from this.
jsonValidateSymbols = true
// jsonEscapeMultiByteUnicodeSep controls whether some unicode characters
// that are valid json but may bomb in some contexts are escaped during encoeing.
//
// U+2028 is LINE SEPARATOR. U+2029 is PARAGRAPH SEPARATOR.
// Both technically valid JSON, but bomb on JSONP, so fix here unconditionally.
jsonEscapeMultiByteUnicodeSep = true
// jsonRecognizeBoolNullInQuotedStr is used during decoding into a blank interface{}
// to control whether we detect quoted values of bools and null where a map key is expected,
// and treat as nil, true or false.
jsonNakedBoolNullInQuotedStr = true
// jsonManualInlineDecRdInHotZones controls whether we manually inline some decReader calls.
//
// encode performance is at par with libraries that just iterate over bytes directly,
// because encWr (with inlined bytesEncAppender calls) is inlined.
// Conversely, decode performance suffers because decRd (with inlined bytesDecReader calls)
// isn't inlinable.
//
// To improve decode performamnce from json:
// - readn1 is only called for \u
// - consequently, to optimize json decoding, we specifically need inlining
// for bytes use-case of some other decReader methods:
// - jsonReadAsisChars, skipWhitespace (advance) and jsonReadNum
// - AND THEN readn3, readn4 (for ull, rue and alse).
// - (readn1 is only called when a char is escaped).
// - without inlining, we still pay the cost of a method invocationK, and this dominates time
// - To mitigate, we manually inline in hot zones
// *excluding places where used sparingly (e.g. nextValueBytes, and other atypical cases)*.
// - jsonReadAsisChars *only* called in: appendStringAsBytes
// - advance called: everywhere
// - jsonReadNum: decNumBytes, DecodeNaked
// - From running go test (our anecdotal findings):
// - calling jsonReadAsisChars in appendStringAsBytes: 23431
// - calling jsonReadNum in decNumBytes: 15251
// - calling jsonReadNum in DecodeNaked: 612
// Consequently, we manually inline jsonReadAsisChars (in appendStringAsBytes)
// and jsonReadNum (in decNumbytes)
jsonManualInlineDecRdInHotZones = true
jsonSpacesOrTabsLen = 128
// jsonAlwaysReturnInternString = false
)
var (
// jsonTabs and jsonSpaces are used as caches for indents
jsonTabs, jsonSpaces [jsonSpacesOrTabsLen]byte
jsonCharHtmlSafeSet bitset256
jsonCharSafeSet bitset256
)
func init() {
var i byte
for i = 0; i < jsonSpacesOrTabsLen; i++ {
jsonSpaces[i] = ' '
jsonTabs[i] = '\t'
}
// populate the safe values as true: note: ASCII control characters are (0-31)
// jsonCharSafeSet: all true except (0-31) " \
// jsonCharHtmlSafeSet: all true except (0-31) " \ < > &
for i = 32; i < utf8.RuneSelf; i++ {
switch i {
case '"', '\\':
case '<', '>', '&':
jsonCharSafeSet.set(i) // = true
default:
jsonCharSafeSet.set(i)
jsonCharHtmlSafeSet.set(i)
}
}
}
// ----------------
type jsonEncState struct {
di int8 // indent per: if negative, use tabs
d bool // indenting?
dl uint16 // indent level
}
func (x jsonEncState) captureState() interface{} { return x }
func (x *jsonEncState) restoreState(v interface{}) { *x = v.(jsonEncState) }
type jsonEncDriver struct {
noBuiltInTypes
h *JsonHandle
// se interfaceExtWrapper
// ---- cpu cache line boundary?
jsonEncState
ks bool // map key as string
is byte // integer as string
typical bool
rawext bool // rawext configured on the handle
s *bitset256 // safe set for characters (taking h.HTMLAsIs into consideration)
// buf *[]byte // used mostly for encoding []byte
// scratch buffer for: encode time, numbers, etc
//
// RFC3339Nano uses 35 chars: 2006-01-02T15:04:05.999999999Z07:00
// MaxUint64 uses 20 chars: 18446744073709551615
// floats are encoded using: f/e fmt, and -1 precision, or 1 if no fractions.
// This means we are limited by the number of characters for the
// mantissa (up to 17), exponent (up to 3), signs (up to 3), dot (up to 1), E (up to 1)
// for a total of 24 characters.
// -xxx.yyyyyyyyyyyye-zzz
// Consequently, 35 characters should be sufficient for encoding time, integers or floats.
// We use up all the remaining bytes to make this use full cache lines.
b [48]byte
e Encoder
}
func (e *jsonEncDriver) encoder() *Encoder { return &e.e }
func (e *jsonEncDriver) writeIndent() {
e.e.encWr.writen1('\n')
x := int(e.di) * int(e.dl)
if e.di < 0 {
x = -x
for x > jsonSpacesOrTabsLen {
e.e.encWr.writeb(jsonTabs[:])
x -= jsonSpacesOrTabsLen
}
e.e.encWr.writeb(jsonTabs[:x])
} else {
for x > jsonSpacesOrTabsLen {
e.e.encWr.writeb(jsonSpaces[:])
x -= jsonSpacesOrTabsLen
}
e.e.encWr.writeb(jsonSpaces[:x])
}
}
func (e *jsonEncDriver) WriteArrayElem() {
if e.e.c != containerArrayStart {
e.e.encWr.writen1(',')
}
if e.d {
e.writeIndent()
}
}
func (e *jsonEncDriver) WriteMapElemKey() {
if e.e.c != containerMapStart {
e.e.encWr.writen1(',')
}
if e.d {
e.writeIndent()
}
}
func (e *jsonEncDriver) WriteMapElemValue() {
if e.d {
e.e.encWr.writen2(':', ' ')
} else {
e.e.encWr.writen1(':')
}
}
func (e *jsonEncDriver) EncodeNil() {
// We always encode nil as just null (never in quotes)
// so we can easily decode if a nil in the json stream ie if initial token is n.
e.e.encWr.writestr(jsonLits[jsonLitN : jsonLitN+4])
}
func (e *jsonEncDriver) EncodeTime(t time.Time) {
// Do NOT use MarshalJSON, as it allocates internally.
// instead, we call AppendFormat directly, using our scratch buffer (e.b)
if t.IsZero() {
e.EncodeNil()
} else {
e.b[0] = '"'
b := fmtTime(t, time.RFC3339Nano, e.b[1:1])
e.b[len(b)+1] = '"'
e.e.encWr.writeb(e.b[:len(b)+2])
}
}
func (e *jsonEncDriver) EncodeExt(rv interface{}, basetype reflect.Type, xtag uint64, ext Ext) {
if ext == SelfExt {
e.e.encodeValue(baseRV(rv), e.h.fnNoExt(basetype))
} else if v := ext.ConvertExt(rv); v == nil {
e.EncodeNil()
} else {
e.e.encode(v)
}
}
func (e *jsonEncDriver) EncodeRawExt(re *RawExt) {
// only encodes re.Value (never re.Data)
if re.Value == nil {
e.EncodeNil()
} else {
e.e.encode(re.Value)
}
}
var jsonEncBoolStrs = [2][2]string{
{jsonLits[jsonLitF : jsonLitF+5], jsonLits[jsonLitT : jsonLitT+4]},
{jsonLits[jsonLitF-1 : jsonLitF+6], jsonLits[jsonLitT-1 : jsonLitT+5]},
}
func (e *jsonEncDriver) EncodeBool(b bool) {
e.e.encWr.writestr(
jsonEncBoolStrs[bool2int(e.ks && e.e.c == containerMapKey)%2][bool2int(b)%2])
}
// func (e *jsonEncDriver) EncodeBool(b bool) {
// if e.ks && e.e.c == containerMapKey {
// if b {
// e.e.encWr.writestr(jsonLits[jsonLitT-1 : jsonLitT+5])
// } else {
// e.e.encWr.writestr(jsonLits[jsonLitF-1 : jsonLitF+6])
// }
// } else {
// if b {
// e.e.encWr.writestr(jsonLits[jsonLitT : jsonLitT+4])
// } else {
// e.e.encWr.writestr(jsonLits[jsonLitF : jsonLitF+5])
// }
// }
// }
func (e *jsonEncDriver) encodeFloat(f float64, bitsize, fmt byte, prec int8) {
var blen uint
if e.ks && e.e.c == containerMapKey {
blen = 2 + uint(len(strconv.AppendFloat(e.b[1:1], f, fmt, int(prec), int(bitsize))))
// _ = e.b[:blen]
e.b[0] = '"'
e.b[blen-1] = '"'
e.e.encWr.writeb(e.b[:blen])
} else {
e.e.encWr.writeb(strconv.AppendFloat(e.b[:0], f, fmt, int(prec), int(bitsize)))
}
}
func (e *jsonEncDriver) EncodeFloat64(f float64) {
if math.IsNaN(f) || math.IsInf(f, 0) {
e.EncodeNil()
return
}
fmt, prec := jsonFloatStrconvFmtPrec64(f)
e.encodeFloat(f, 64, fmt, prec)
}
func (e *jsonEncDriver) EncodeFloat32(f float32) {
if math.IsNaN(float64(f)) || math.IsInf(float64(f), 0) {
e.EncodeNil()
return
}
fmt, prec := jsonFloatStrconvFmtPrec32(f)
e.encodeFloat(float64(f), 32, fmt, prec)
}
func (e *jsonEncDriver) encodeUint(neg bool, quotes bool, u uint64) {
// copied mostly from std library: strconv
// this should only be called on 64bit OS.
// const smallsString = jsonEncodeUintSmallsString
var ss = jsonEncodeUintSmallsStringBytes
// typically, 19 or 20 bytes sufficient for decimal encoding a uint64
// var a [24]byte
var a = e.b[0:24]
var i = uint(len(a))
if quotes {
i--
setByteAt(a, i, '"')
// a[i] = '"'
}
// u guaranteed to fit into a uint (as we are not 32bit OS)
var is uint
var us = uint(u)
for us >= 100 {
is = us % 100 * 2
us /= 100
i -= 2
setByteAt(a, i+1, byteAt(ss, is+1))
setByteAt(a, i, byteAt(ss, is))
// a[i+1] = smallsString[is+1]
// a[i+0] = smallsString[is+0]
}
// us < 100
is = us * 2
i--
setByteAt(a, i, byteAt(ss, is+1))
// a[i] = smallsString[is+1]
if us >= 10 {
i--
setByteAt(a, i, byteAt(ss, is))
// a[i] = smallsString[is]
}
if neg {
i--
setByteAt(a, i, '-')
// a[i] = '-'
}
if quotes {
i--
setByteAt(a, i, '"')
// a[i] = '"'
}
e.e.encWr.writeb(a[i:])
}
func (e *jsonEncDriver) EncodeInt(v int64) {
quotes := e.is == 'A' || e.is == 'L' && (v > 1<<53 || v < -(1<<53)) ||
(e.ks && e.e.c == containerMapKey)
if cpu32Bit {
if quotes {
blen := 2 + len(strconv.AppendInt(e.b[1:1], v, 10))
e.b[0] = '"'
e.b[blen-1] = '"'
e.e.encWr.writeb(e.b[:blen])
} else {
e.e.encWr.writeb(strconv.AppendInt(e.b[:0], v, 10))
}
return
}
if v < 0 {
e.encodeUint(true, quotes, uint64(-v))
} else {
e.encodeUint(false, quotes, uint64(v))
}
}
func (e *jsonEncDriver) EncodeUint(v uint64) {
quotes := e.is == 'A' || e.is == 'L' && v > 1<<53 ||
(e.ks && e.e.c == containerMapKey)
if cpu32Bit {
// use strconv directly, as optimized encodeUint only works on 64-bit alone
if quotes {
blen := 2 + len(strconv.AppendUint(e.b[1:1], v, 10))
e.b[0] = '"'
e.b[blen-1] = '"'
e.e.encWr.writeb(e.b[:blen])
} else {
e.e.encWr.writeb(strconv.AppendUint(e.b[:0], v, 10))
}
return
}
e.encodeUint(false, quotes, v)
}
func (e *jsonEncDriver) EncodeString(v string) {
if e.h.StringToRaw {
e.EncodeStringBytesRaw(bytesView(v))
return
}
e.quoteStr(v)
}
func (e *jsonEncDriver) EncodeStringBytesRaw(v []byte) {
// if encoding raw bytes and RawBytesExt is configured, use it to encode
if v == nil {
e.EncodeNil()
return
}
if e.rawext {
iv := e.h.RawBytesExt.ConvertExt(v)
if iv == nil {
e.EncodeNil()
} else {
e.e.encode(iv)
}
return
}
slen := base64.StdEncoding.EncodedLen(len(v)) + 2
// bs := e.e.blist.check(*e.buf, n)[:slen]
// *e.buf = bs
bs := e.e.blist.peek(slen, false)
bs = bs[:slen]
base64.StdEncoding.Encode(bs[1:], v)
bs[len(bs)-1] = '"'
bs[0] = '"'
e.e.encWr.writeb(bs)
}
// indent is done as below:
// - newline and indent are added before each mapKey or arrayElem
// - newline and indent are added before each ending,
// except there was no entry (so we can have {} or [])
func (e *jsonEncDriver) WriteArrayStart(length int) {
if e.d {
e.dl++
}
e.e.encWr.writen1('[')
}
func (e *jsonEncDriver) WriteArrayEnd() {
if e.d {
e.dl--
e.writeIndent()
}
e.e.encWr.writen1(']')
}
func (e *jsonEncDriver) WriteMapStart(length int) {
if e.d {
e.dl++
}
e.e.encWr.writen1('{')
}
func (e *jsonEncDriver) WriteMapEnd() {
if e.d {
e.dl--
if e.e.c != containerMapStart {
e.writeIndent()
}
}
e.e.encWr.writen1('}')
}
func (e *jsonEncDriver) quoteStr(s string) {
// adapted from std pkg encoding/json
const hex = "0123456789abcdef"
w := e.e.w()
w.writen1('"')
var i, start uint
for i < uint(len(s)) {
// encode all bytes < 0x20 (except \r, \n).
// also encode < > & to prevent security holes when served to some browsers.
// We optimize for ascii, by assumining that most characters are in the BMP
// and natively consumed by json without much computation.
// if 0x20 <= b && b != '\\' && b != '"' && b != '<' && b != '>' && b != '&' {
// if (htmlasis && jsonCharSafeSet.isset(b)) || jsonCharHtmlSafeSet.isset(b) {
if e.s.isset(s[i]) {
i++
continue
}
// b := s[i]
if s[i] < utf8.RuneSelf {
if start < i {
w.writestr(s[start:i])
}
switch s[i] {
case '\\', '"':
w.writen2('\\', s[i])
case '\n':
w.writen2('\\', 'n')
case '\r':
w.writen2('\\', 'r')
case '\b':
w.writen2('\\', 'b')
case '\f':
w.writen2('\\', 'f')
case '\t':
w.writen2('\\', 't')
default:
w.writestr(`\u00`)
w.writen2(hex[s[i]>>4], hex[s[i]&0xF])
}
i++
start = i
continue
}
c, size := utf8.DecodeRuneInString(s[i:])
if c == utf8.RuneError && size == 1 { // meaning invalid encoding (so output as-is)
if start < i {
w.writestr(s[start:i])
}
w.writestr(`\uFFFD`)
i++
start = i
continue
}
// U+2028 is LINE SEPARATOR. U+2029 is PARAGRAPH SEPARATOR.
// Both technically valid JSON, but bomb on JSONP, so fix here *unconditionally*.
if jsonEscapeMultiByteUnicodeSep && (c == '\u2028' || c == '\u2029') {
if start < i {
w.writestr(s[start:i])
}
w.writestr(`\u202`)
w.writen1(hex[c&0xF])
i += uint(size)
start = i
continue
}
i += uint(size)
}
if start < uint(len(s)) {
w.writestr(s[start:])
}
w.writen1('"')
}
func (e *jsonEncDriver) atEndOfEncode() {
if e.h.TermWhitespace {
var c byte = ' ' // default is that scalar is written, so output space
if e.e.c != 0 {
c = '\n' // for containers (map/list), output a newline
}
e.e.encWr.writen1(c)
}
}
// ----------
type jsonDecState struct {
rawext bool // rawext configured on the handle
tok uint8 // used to store the token read right after skipWhiteSpace
_ bool // found null
_ byte // padding
bstr [4]byte // scratch used for string \UXXX parsing
// scratch buffer used for base64 decoding (DecodeBytes in reuseBuf mode),
// or reading doubleQuoted string (DecodeStringAsBytes, DecodeNaked)
buf *[]byte
}
func (x jsonDecState) captureState() interface{} { return x }
func (x *jsonDecState) restoreState(v interface{}) { *x = v.(jsonDecState) }
type jsonDecDriver struct {
noBuiltInTypes
decDriverNoopNumberHelper
h *JsonHandle
jsonDecState
// se interfaceExtWrapper
// ---- cpu cache line boundary?
d Decoder
}
func (d *jsonDecDriver) descBd() (s string) { panic("descBd unsupported") }
func (d *jsonDecDriver) decoder() *Decoder {
return &d.d
}
func (d *jsonDecDriver) ReadMapStart() int {
d.advance()
if d.tok == 'n' {
d.checkLit3([3]byte{'u', 'l', 'l'}, d.d.decRd.readn3())
return containerLenNil
}
if d.tok != '{' {
d.d.errorf("read map - expect char '%c' but got char '%c'", '{', d.tok)
}
d.tok = 0
return containerLenUnknown
}
func (d *jsonDecDriver) ReadArrayStart() int {
d.advance()
if d.tok == 'n' {
d.checkLit3([3]byte{'u', 'l', 'l'}, d.d.decRd.readn3())
return containerLenNil
}
if d.tok != '[' {
d.d.errorf("read array - expect char '%c' but got char '%c'", '[', d.tok)
}
d.tok = 0
return containerLenUnknown
}
// MARKER:
// We attempted making sure CheckBreak can be inlined, by moving the skipWhitespace
// call to an explicit (noinline) function call.
// However, this forces CheckBreak to always incur a function call if there was whitespace,
// with no clear benefit.
func (d *jsonDecDriver) CheckBreak() bool {
d.advance()
return d.tok == '}' || d.tok == ']'
}
func (d *jsonDecDriver) ReadArrayElem() {
const xc uint8 = ','
if d.d.c != containerArrayStart {
d.advance()
if d.tok != xc {
d.readDelimError(xc)
}
d.tok = 0
}
}
func (d *jsonDecDriver) ReadArrayEnd() {
const xc uint8 = ']'
d.advance()
if d.tok != xc {
d.readDelimError(xc)
}
d.tok = 0
}
func (d *jsonDecDriver) ReadMapElemKey() {
const xc uint8 = ','
if d.d.c != containerMapStart {
d.advance()
if d.tok != xc {
d.readDelimError(xc)
}
d.tok = 0
}
}
func (d *jsonDecDriver) ReadMapElemValue() {
const xc uint8 = ':'
d.advance()
if d.tok != xc {
d.readDelimError(xc)
}
d.tok = 0
}
func (d *jsonDecDriver) ReadMapEnd() {
const xc uint8 = '}'
d.advance()
if d.tok != xc {
d.readDelimError(xc)
}
d.tok = 0
}
func (d *jsonDecDriver) readDelimError(xc uint8) {
d.d.errorf("read json delimiter - expect char '%c' but got char '%c'", xc, d.tok)
}
// MARKER: checkLit takes the readn(3|4) result as a parameter so they can be inlined.
// We pass the array directly to errorf, as passing slice pushes past inlining threshold,
// and passing slice also might cause allocation of the bs array on the heap.
func (d *jsonDecDriver) checkLit3(got, expect [3]byte) {
d.tok = 0
if jsonValidateSymbols && got != expect {
d.d.errorf("expecting %s: got %s", expect, got)
}
}
func (d *jsonDecDriver) checkLit4(got, expect [4]byte) {
d.tok = 0
if jsonValidateSymbols && got != expect {
d.d.errorf("expecting %s: got %s", expect, got)
}
}
func (d *jsonDecDriver) skipWhitespace() {
d.tok = d.d.decRd.skipWhitespace()
}
func (d *jsonDecDriver) advance() {
if d.tok == 0 {
d.skipWhitespace()
}
}
func (d *jsonDecDriver) nextValueBytes(v []byte) []byte {
v, cursor := d.nextValueBytesR(v)
decNextValueBytesHelper{d: &d.d}.bytesRdV(&v, cursor)
return v
}
func (d *jsonDecDriver) nextValueBytesR(v0 []byte) (v []byte, cursor uint) {
v = v0
var h = decNextValueBytesHelper{d: &d.d}
dr := &d.d.decRd
consumeString := func() {
TOP:
bs := dr.jsonReadAsisChars()
h.appendN(&v, bs...)
if bs[len(bs)-1] != '"' {
// last char is '\', so consume next one and try again
h.append1(&v, dr.readn1())
goto TOP
}
}
d.advance() // ignore leading whitespace
cursor = d.d.rb.c - 1 // cursor starts just before non-whitespace token
switch d.tok {
default:
h.appendN(&v, dr.jsonReadNum()...)
case 'n':
d.checkLit3([3]byte{'u', 'l', 'l'}, d.d.decRd.readn3())
h.appendS(&v, jsonLits[jsonLitN:jsonLitN+4])
case 'f':
d.checkLit4([4]byte{'a', 'l', 's', 'e'}, d.d.decRd.readn4())
h.appendS(&v, jsonLits[jsonLitF:jsonLitF+5])
case 't':
d.checkLit3([3]byte{'r', 'u', 'e'}, d.d.decRd.readn3())
h.appendS(&v, jsonLits[jsonLitT:jsonLitT+4])
case '"':
h.append1(&v, '"')
consumeString()
case '{', '[':
var elem struct{}
var stack []struct{}
stack = append(stack, elem)
h.append1(&v, d.tok)
for len(stack) != 0 {
c := dr.readn1()
h.append1(&v, c)
switch c {
case '"':
consumeString()
case '{', '[':
stack = append(stack, elem)
case '}', ']':
stack = stack[:len(stack)-1]
}
}
}
d.tok = 0
return
}
func (d *jsonDecDriver) TryNil() bool {
d.advance()
// we shouldn't try to see if quoted "null" was here, right?
// only the plain string: `null` denotes a nil (ie not quotes)
if d.tok == 'n' {
d.checkLit3([3]byte{'u', 'l', 'l'}, d.d.decRd.readn3())
return true
}
return false
}
func (d *jsonDecDriver) DecodeBool() (v bool) {
d.advance()
// bool can be in quotes if and only if it's a map key
fquot := d.d.c == containerMapKey && d.tok == '"'
if fquot {
d.tok = d.d.decRd.readn1()
}
switch d.tok {
case 'f':
d.checkLit4([4]byte{'a', 'l', 's', 'e'}, d.d.decRd.readn4())
// v = false
case 't':
d.checkLit3([3]byte{'r', 'u', 'e'}, d.d.decRd.readn3())
v = true
case 'n':
d.checkLit3([3]byte{'u', 'l', 'l'}, d.d.decRd.readn3())
// v = false
default:
d.d.errorf("decode bool: got first char %c", d.tok)
// v = false // "unreachable"
}
if fquot {
d.d.decRd.readn1()
}
return
}
func (d *jsonDecDriver) DecodeTime() (t time.Time) {
// read string, and pass the string into json.unmarshal
d.advance()
if d.tok == 'n' {
d.checkLit3([3]byte{'u', 'l', 'l'}, d.d.decRd.readn3())
return
}
d.ensureReadingString()
bs := d.readUnescapedString()
t, err := time.Parse(time.RFC3339, stringView(bs))
d.d.onerror(err)
return
}
func (d *jsonDecDriver) ContainerType() (vt valueType) {
// check container type by checking the first char
d.advance()
// optimize this, so we don't do 4 checks but do one computation.
// return jsonContainerSet[d.tok]
// ContainerType is mostly called for Map and Array,
// so this conditional is good enough (max 2 checks typically)
if d.tok == '{' {
return valueTypeMap
} else if d.tok == '[' {
return valueTypeArray
} else if d.tok == 'n' {
d.checkLit3([3]byte{'u', 'l', 'l'}, d.d.decRd.readn3())
return valueTypeNil
} else if d.tok == '"' {
return valueTypeString
}
return valueTypeUnset
}
func (d *jsonDecDriver) decNumBytes() (bs []byte) {
d.advance()
dr := &d.d.decRd
if d.tok == '"' {
bs = dr.readUntil('"')
} else if d.tok == 'n' {
d.checkLit3([3]byte{'u', 'l', 'l'}, dr.readn3())
} else {
if jsonManualInlineDecRdInHotZones {
if dr.bytes {
bs = dr.rb.jsonReadNum()
} else {
bs = dr.ri.jsonReadNum()
}
} else {
bs = dr.jsonReadNum()
}
}
d.tok = 0
return
}
func (d *jsonDecDriver) DecodeUint64() (u uint64) {
b := d.decNumBytes()
u, neg, ok := parseInteger_bytes(b)
if neg {
d.d.errorf("negative number cannot be decoded as uint64")
}
if !ok {
d.d.onerror(strconvParseErr(b, "ParseUint"))
}
return
}
func (d *jsonDecDriver) DecodeInt64() (v int64) {
b := d.decNumBytes()
u, neg, ok := parseInteger_bytes(b)
if !ok {
d.d.onerror(strconvParseErr(b, "ParseInt"))
}
if chkOvf.Uint2Int(u, neg) {
d.d.errorf("overflow decoding number from %s", b)
}
if neg {
v = -int64(u)
} else {
v = int64(u)
}
return
}
func (d *jsonDecDriver) DecodeFloat64() (f float64) {
var err error
bs := d.decNumBytes()
if len(bs) == 0 {
return
}
f, err = parseFloat64(bs)
d.d.onerror(err)
return
}
func (d *jsonDecDriver) DecodeFloat32() (f float32) {
var err error
bs := d.decNumBytes()
if len(bs) == 0 {
return
}
f, err = parseFloat32(bs)
d.d.onerror(err)
return
}
func (d *jsonDecDriver) DecodeExt(rv interface{}, basetype reflect.Type, xtag uint64, ext Ext) {
d.advance()
if d.tok == 'n' {
d.checkLit3([3]byte{'u', 'l', 'l'}, d.d.decRd.readn3())
return
}
if ext == nil {
re := rv.(*RawExt)
re.Tag = xtag
d.d.decode(&re.Value)
} else if ext == SelfExt {
d.d.decodeValue(baseRV(rv), d.h.fnNoExt(basetype))
} else {
d.d.interfaceExtConvertAndDecode(rv, ext)
}
}
func (d *jsonDecDriver) decBytesFromArray(bs []byte) []byte {
if bs != nil {
bs = bs[:0]
}
d.tok = 0
bs = append(bs, uint8(d.DecodeUint64()))
d.tok = d.d.decRd.skipWhitespace() // skip(&whitespaceCharBitset)
for d.tok != ']' {
if d.tok != ',' {
d.d.errorf("read array element - expect char '%c' but got char '%c'", ',', d.tok)
}
d.tok = 0
bs = append(bs, uint8(chkOvf.UintV(d.DecodeUint64(), 8)))
d.tok = d.d.decRd.skipWhitespace() // skip(&whitespaceCharBitset)
}
d.tok = 0
return bs
}
func (d *jsonDecDriver) DecodeBytes(bs []byte) (bsOut []byte) {
d.d.decByteState = decByteStateNone
d.advance()
if d.tok == 'n' {
d.checkLit3([3]byte{'u', 'l', 'l'}, d.d.decRd.readn3())
return nil
}
// if decoding into raw bytes, and the RawBytesExt is configured, use it to decode.
if d.rawext {
bsOut = bs
d.d.interfaceExtConvertAndDecode(&bsOut, d.h.RawBytesExt)
return
}
// check if an "array" of uint8's (see ContainerType for how to infer if an array)
if d.tok == '[' {
// bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d)
if bs == nil {
d.d.decByteState = decByteStateReuseBuf
bs = d.d.b[:]
}
return d.decBytesFromArray(bs)
}
// base64 encodes []byte{} as "", and we encode nil []byte as null.
// Consequently, base64 should decode null as a nil []byte, and "" as an empty []byte{}.
d.ensureReadingString()
bs1 := d.readUnescapedString()
slen := base64.StdEncoding.DecodedLen(len(bs1))
if slen == 0 {
bsOut = []byte{}
} else if slen <= cap(bs) {
bsOut = bs[:slen]
} else if bs == nil {
d.d.decByteState = decByteStateReuseBuf
bsOut = d.d.blist.check(*d.buf, slen)
bsOut = bsOut[:slen]
*d.buf = bsOut
} else {
bsOut = make([]byte, slen)
}
slen2, err := base64.StdEncoding.Decode(bsOut, bs1)
if err != nil {
d.d.errorf("error decoding base64 binary '%s': %v", bs1, err)
}
if slen != slen2 {
bsOut = bsOut[:slen2]
}
return
}
func (d *jsonDecDriver) DecodeStringAsBytes() (s []byte) {
d.d.decByteState = decByteStateNone
d.advance()
// common case - hoist outside the switch statement
if d.tok == '"' {
return d.dblQuoteStringAsBytes()
}
// handle non-string scalar: null, true, false or a number
switch d.tok {
case 'n':
d.checkLit3([3]byte{'u', 'l', 'l'}, d.d.decRd.readn3())
return nil // []byte{}
case 'f':
d.checkLit4([4]byte{'a', 'l', 's', 'e'}, d.d.decRd.readn4())
return jsonLitb[jsonLitF : jsonLitF+5]
case 't':
d.checkLit3([3]byte{'r', 'u', 'e'}, d.d.decRd.readn3())
return jsonLitb[jsonLitT : jsonLitT+4]
default:
// try to parse a valid number
d.tok = 0
return d.d.decRd.jsonReadNum()
}
}
func (d *jsonDecDriver) ensureReadingString() {
if d.tok != '"' {
d.d.errorf("expecting string starting with '\"'; got '%c'", d.tok)
}
}
func (d *jsonDecDriver) readUnescapedString() (bs []byte) {
// d.ensureReadingString()
bs = d.d.decRd.readUntil('"')
d.tok = 0
return
}
func (d *jsonDecDriver) dblQuoteStringAsBytes() (buf []byte) {
checkUtf8 := d.h.ValidateUnicode
d.d.decByteState = decByteStateNone
// use a local buf variable, so we don't do pointer chasing within loop
buf = (*d.buf)[:0]
dr := &d.d.decRd
d.tok = 0
var bs []byte
var c byte
var firstTime bool = true
for {
if firstTime {
firstTime = false
if dr.bytes {
bs = dr.rb.jsonReadAsisChars()
if bs[len(bs)-1] == '"' {
d.d.decByteState = decByteStateZerocopy
return bs[:len(bs)-1]
}
goto APPEND
}
}
if jsonManualInlineDecRdInHotZones {
if dr.bytes {
bs = dr.rb.jsonReadAsisChars()
} else {
bs = dr.ri.jsonReadAsisChars()
}
} else {
bs = dr.jsonReadAsisChars()
}
APPEND:
_ = bs[0] // bounds check hint - slice must be > 0 elements
buf = append(buf, bs[:len(bs)-1]...)
c = bs[len(bs)-1]
if c == '"' {
break
}
// c is now '\'
c = dr.readn1()
switch c {
case '"', '\\', '/', '\'':
buf = append(buf, c)
case 'b':
buf = append(buf, '\b')
case 'f':
buf = append(buf, '\f')
case 'n':
buf = append(buf, '\n')
case 'r':
buf = append(buf, '\r')
case 't':
buf = append(buf, '\t')
case 'u':
rr := d.appendStringAsBytesSlashU()
if checkUtf8 && rr == unicode.ReplacementChar {
d.d.errorf("invalid UTF-8 character found after: %s", buf)
}
buf = append(buf, d.bstr[:utf8.EncodeRune(d.bstr[:], rr)]...)
default:
*d.buf = buf
d.d.errorf("unsupported escaped value: %c", c)
}
}
*d.buf = buf
d.d.decByteState = decByteStateReuseBuf
return
}
func (d *jsonDecDriver) appendStringAsBytesSlashU() (r rune) {
var rr uint32
var csu [2]byte
var cs [4]byte = d.d.decRd.readn4()
if rr = jsonSlashURune(cs); rr == unicode.ReplacementChar {
return unicode.ReplacementChar
}
r = rune(rr)
if utf16.IsSurrogate(r) {
csu = d.d.decRd.readn2()
cs = d.d.decRd.readn4()
if csu[0] == '\\' && csu[1] == 'u' {
if rr = jsonSlashURune(cs); rr == unicode.ReplacementChar {
return unicode.ReplacementChar
}
return utf16.DecodeRune(r, rune(rr))
}
return unicode.ReplacementChar
}
return
}
func jsonSlashURune(cs [4]byte) (rr uint32) {
for _, c := range cs {
// best to use explicit if-else
// - not a table, etc which involve memory loads, array lookup with bounds checks, etc
if c >= '0' && c <= '9' {
rr = rr*16 + uint32(c-jsonU4Chk2)
} else if c >= 'a' && c <= 'f' {
rr = rr*16 + uint32(c-jsonU4Chk1)
} else if c >= 'A' && c <= 'F' {
rr = rr*16 + uint32(c-jsonU4Chk0)
} else {
return unicode.ReplacementChar
}
}
return
}
func (d *jsonDecDriver) nakedNum(z *fauxUnion, bs []byte) (err error) {
// Note: nakedNum is NEVER called with a zero-length []byte
if d.h.PreferFloat {
z.v = valueTypeFloat
z.f, err = parseFloat64(bs)
} else {
err = parseNumber(bs, z, d.h.SignedInteger)
}
return
}
func (d *jsonDecDriver) DecodeNaked() {
z := d.d.naked()
d.advance()
var bs []byte
switch d.tok {
case 'n':
d.checkLit3([3]byte{'u', 'l', 'l'}, d.d.decRd.readn3())
z.v = valueTypeNil
case 'f':
d.checkLit4([4]byte{'a', 'l', 's', 'e'}, d.d.decRd.readn4())
z.v = valueTypeBool
z.b = false
case 't':
d.checkLit3([3]byte{'r', 'u', 'e'}, d.d.decRd.readn3())
z.v = valueTypeBool
z.b = true
case '{':
z.v = valueTypeMap // don't consume. kInterfaceNaked will call ReadMapStart
case '[':
z.v = valueTypeArray // don't consume. kInterfaceNaked will call ReadArrayStart
case '"':
// if a string, and MapKeyAsString, then try to decode it as a bool or number first
bs = d.dblQuoteStringAsBytes()
if jsonNakedBoolNullInQuotedStr &&
d.h.MapKeyAsString && len(bs) > 0 && d.d.c == containerMapKey {
switch string(bs) {
// case "null": // nil is never quoted
// z.v = valueTypeNil
case "true":
z.v = valueTypeBool
z.b = true
case "false":
z.v = valueTypeBool
z.b = false
default:
// check if a number: float, int or uint
if err := d.nakedNum(z, bs); err != nil {
z.v = valueTypeString
z.s = d.d.stringZC(bs)
}
}
} else {
z.v = valueTypeString
z.s = d.d.stringZC(bs)
}
default: // number
bs = d.d.decRd.jsonReadNum()
d.tok = 0
if len(bs) == 0 {
d.d.errorf("decode number from empty string")
}
if err := d.nakedNum(z, bs); err != nil {
d.d.errorf("decode number from %s: %v", bs, err)
}
}
}
//----------------------
// JsonHandle is a handle for JSON encoding format.
//
// Json is comprehensively supported:
// - decodes numbers into interface{} as int, uint or float64
// based on how the number looks and some config parameters e.g. PreferFloat, SignedInt, etc.
// - decode integers from float formatted numbers e.g. 1.27e+8
// - decode any json value (numbers, bool, etc) from quoted strings
// - configurable way to encode/decode []byte .
// by default, encodes and decodes []byte using base64 Std Encoding
// - UTF-8 support for encoding and decoding
//
// It has better performance than the json library in the standard library,
// by leveraging the performance improvements of the codec library.
//
// In addition, it doesn't read more bytes than necessary during a decode, which allows
// reading multiple values from a stream containing json and non-json content.
// For example, a user can read a json value, then a cbor value, then a msgpack value,
// all from the same stream in sequence.
//
// Note that, when decoding 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.
//
// Note also that the float values for NaN, +Inf or -Inf are encoded as null,
// as suggested by NOTE 4 of the ECMA-262 ECMAScript Language Specification 5.1 edition.
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | true |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ugorji/go/codec/decimal.go | vendor/github.com/ugorji/go/codec/decimal.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
package codec
import (
"math"
"strconv"
)
// Per go spec, floats are represented in memory as
// IEEE single or double precision floating point values.
//
// We also looked at the source for stdlib math/modf.go,
// reviewed https://github.com/chewxy/math32
// and read wikipedia documents describing the formats.
//
// It became clear that we could easily look at the bits to determine
// whether any fraction exists.
func parseFloat32(b []byte) (f float32, err error) {
return parseFloat32_custom(b)
}
func parseFloat64(b []byte) (f float64, err error) {
return parseFloat64_custom(b)
}
func parseFloat32_strconv(b []byte) (f float32, err error) {
f64, err := strconv.ParseFloat(stringView(b), 32)
f = float32(f64)
return
}
func parseFloat64_strconv(b []byte) (f float64, err error) {
return strconv.ParseFloat(stringView(b), 64)
}
// ------ parseFloat custom below --------
// JSON really supports decimal numbers in base 10 notation, with exponent support.
//
// We assume the following:
// - a lot of floating point numbers in json files will have defined precision
// (in terms of number of digits after decimal point), etc.
// - these (referenced above) can be written in exact format.
//
// strconv.ParseFloat has some unnecessary overhead which we can do without
// for the common case:
//
// - expensive char-by-char check to see if underscores are in right place
// - testing for and skipping underscores
// - check if the string matches ignorecase +/- inf, +/- infinity, nan
// - support for base 16 (0xFFFF...)
//
// The functions below will try a fast-path for floats which can be decoded
// without any loss of precision, meaning they:
//
// - fits within the significand bits of the 32-bits or 64-bits
// - exponent fits within the exponent value
// - there is no truncation (any extra numbers are all trailing zeros)
//
// To figure out what the values are for maxMantDigits, use this idea below:
//
// 2^23 = 838 8608 (between 10^ 6 and 10^ 7) (significand bits of uint32)
// 2^32 = 42 9496 7296 (between 10^ 9 and 10^10) (full uint32)
// 2^52 = 4503 5996 2737 0496 (between 10^15 and 10^16) (significand bits of uint64)
// 2^64 = 1844 6744 0737 0955 1616 (between 10^19 and 10^20) (full uint64)
//
// Note: we only allow for up to what can comfortably fit into the significand
// ignoring the exponent, and we only try to parse iff significand fits.
const (
fMaxMultiplierForExactPow10_64 = 1e15
fMaxMultiplierForExactPow10_32 = 1e7
fUint64Cutoff = (1<<64-1)/10 + 1
// fUint32Cutoff = (1<<32-1)/10 + 1
fBase = 10
)
const (
thousand = 1000
million = thousand * thousand
billion = thousand * million
trillion = thousand * billion
quadrillion = thousand * trillion
quintillion = thousand * quadrillion
)
// Exact powers of 10.
var uint64pow10 = [...]uint64{
1, 10, 100,
1 * thousand, 10 * thousand, 100 * thousand,
1 * million, 10 * million, 100 * million,
1 * billion, 10 * billion, 100 * billion,
1 * trillion, 10 * trillion, 100 * trillion,
1 * quadrillion, 10 * quadrillion, 100 * quadrillion,
1 * quintillion, 10 * quintillion,
}
var float64pow10 = [...]float64{
1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
1e20, 1e21, 1e22,
}
var float32pow10 = [...]float32{
1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10,
}
type floatinfo struct {
mantbits uint8
// expbits uint8 // (unused)
// bias int16 // (unused)
// is32bit bool // (unused)
exactPow10 int8 // Exact powers of ten are <= 10^N (32: 10, 64: 22)
exactInts int8 // Exact integers are <= 10^N (for non-float, set to 0)
// maxMantDigits int8 // 10^19 fits in uint64, while 10^9 fits in uint32
mantCutoffIsUint64Cutoff bool
mantCutoff uint64
}
var fi32 = floatinfo{23, 10, 7, false, 1<<23 - 1}
var fi64 = floatinfo{52, 22, 15, false, 1<<52 - 1}
var fi64u = floatinfo{0, 19, 0, true, fUint64Cutoff}
func noFrac64(fbits uint64) bool {
if fbits == 0 {
return true
}
exp := uint64(fbits>>52)&0x7FF - 1023 // uint(x>>shift)&mask - bias
// clear top 12+e bits, the integer part; if the rest is 0, then no fraction.
return exp < 52 && fbits<<(12+exp) == 0 // means there's no fractional part
}
func noFrac32(fbits uint32) bool {
if fbits == 0 {
return true
}
exp := uint32(fbits>>23)&0xFF - 127 // uint(x>>shift)&mask - bias
// clear top 9+e bits, the integer part; if the rest is 0, then no fraction.
return exp < 23 && fbits<<(9+exp) == 0 // means there's no fractional part
}
func strconvParseErr(b []byte, fn string) error {
return &strconv.NumError{
Func: fn,
Err: strconv.ErrSyntax,
Num: string(b),
}
}
func parseFloat32_reader(r readFloatResult) (f float32, fail bool) {
f = float32(r.mantissa)
if r.exp == 0 {
} else if r.exp < 0 { // int / 10^k
f /= float32pow10[uint8(-r.exp)]
} else { // exp > 0
if r.exp > fi32.exactPow10 {
f *= float32pow10[r.exp-fi32.exactPow10]
if f > fMaxMultiplierForExactPow10_32 { // exponent too large - outside range
fail = true
return // ok = false
}
f *= float32pow10[fi32.exactPow10]
} else {
f *= float32pow10[uint8(r.exp)]
}
}
if r.neg {
f = -f
}
return
}
func parseFloat32_custom(b []byte) (f float32, err error) {
r := readFloat(b, fi32)
if r.bad {
return 0, strconvParseErr(b, "ParseFloat")
}
if r.ok {
f, r.bad = parseFloat32_reader(r)
if !r.bad {
return
}
}
return parseFloat32_strconv(b)
}
func parseFloat64_reader(r readFloatResult) (f float64, fail bool) {
f = float64(r.mantissa)
if r.exp == 0 {
} else if r.exp < 0 { // int / 10^k
f /= float64pow10[-uint8(r.exp)]
} else { // exp > 0
if r.exp > fi64.exactPow10 {
f *= float64pow10[r.exp-fi64.exactPow10]
if f > fMaxMultiplierForExactPow10_64 { // exponent too large - outside range
fail = true
return
}
f *= float64pow10[fi64.exactPow10]
} else {
f *= float64pow10[uint8(r.exp)]
}
}
if r.neg {
f = -f
}
return
}
func parseFloat64_custom(b []byte) (f float64, err error) {
r := readFloat(b, fi64)
if r.bad {
return 0, strconvParseErr(b, "ParseFloat")
}
if r.ok {
f, r.bad = parseFloat64_reader(r)
if !r.bad {
return
}
}
return parseFloat64_strconv(b)
}
func parseUint64_simple(b []byte) (n uint64, ok bool) {
var i int
var n1 uint64
var c uint8
LOOP:
if i < len(b) {
c = b[i]
// unsigned integers don't overflow well on multiplication, so check cutoff here
// e.g. (maxUint64-5)*10 doesn't overflow well ...
// if n >= fUint64Cutoff || !isDigitChar(b[i]) { // if c < '0' || c > '9' {
if n >= fUint64Cutoff || c < '0' || c > '9' {
return
} else if c == '0' {
n *= fBase
} else {
n1 = n
n = n*fBase + uint64(c-'0')
if n < n1 {
return
}
}
i++
goto LOOP
}
ok = true
return
}
func parseUint64_reader(r readFloatResult) (f uint64, fail bool) {
f = r.mantissa
if r.exp == 0 {
} else if r.exp < 0 { // int / 10^k
if f%uint64pow10[uint8(-r.exp)] != 0 {
fail = true
} else {
f /= uint64pow10[uint8(-r.exp)]
}
} else { // exp > 0
f *= uint64pow10[uint8(r.exp)]
}
return
}
func parseInteger_bytes(b []byte) (u uint64, neg, ok bool) {
if len(b) == 0 {
ok = true
return
}
if b[0] == '-' {
if len(b) == 1 {
return
}
neg = true
b = b[1:]
}
u, ok = parseUint64_simple(b)
if ok {
return
}
r := readFloat(b, fi64u)
if r.ok {
var fail bool
u, fail = parseUint64_reader(r)
if fail {
f, err := parseFloat64(b)
if err != nil {
return
}
if !noFrac64(math.Float64bits(f)) {
return
}
u = uint64(f)
}
ok = true
return
}
return
}
// parseNumber will return an integer if only composed of [-]?[0-9]+
// Else it will return a float.
func parseNumber(b []byte, z *fauxUnion, preferSignedInt bool) (err error) {
var ok, neg bool
var f uint64
if len(b) == 0 {
return
}
if b[0] == '-' {
neg = true
f, ok = parseUint64_simple(b[1:])
} else {
f, ok = parseUint64_simple(b)
}
if ok {
if neg {
z.v = valueTypeInt
if chkOvf.Uint2Int(f, neg) {
return strconvParseErr(b, "ParseInt")
}
z.i = -int64(f)
} else if preferSignedInt {
z.v = valueTypeInt
if chkOvf.Uint2Int(f, neg) {
return strconvParseErr(b, "ParseInt")
}
z.i = int64(f)
} else {
z.v = valueTypeUint
z.u = f
}
return
}
z.v = valueTypeFloat
z.f, err = parseFloat64_custom(b)
return
}
type readFloatResult struct {
mantissa uint64
exp int8
neg bool
trunc bool
bad bool // bad decimal string
hardexp bool // exponent is hard to handle (> 2 digits, etc)
ok bool
// sawdot bool
// sawexp bool
//_ [2]bool // padding
}
func readFloat(s []byte, y floatinfo) (r readFloatResult) {
var i uint // uint, so that we eliminate bounds checking
var slen = uint(len(s))
if slen == 0 {
// read an empty string as the zero value
// r.bad = true
r.ok = true
return
}
if s[0] == '-' {
r.neg = true
i++
}
// we considered punting early if string has length > maxMantDigits, but this doesn't account
// for trailing 0's e.g. 700000000000000000000 can be encoded exactly as it is 7e20
var nd, ndMant, dp int8
var sawdot, sawexp bool
var xu uint64
LOOP:
for ; i < slen; i++ {
switch s[i] {
case '.':
if sawdot {
r.bad = true
return
}
sawdot = true
dp = nd
case 'e', 'E':
sawexp = true
break LOOP
case '0':
if nd == 0 {
dp--
continue LOOP
}
nd++
if r.mantissa < y.mantCutoff {
r.mantissa *= fBase
ndMant++
}
case '1', '2', '3', '4', '5', '6', '7', '8', '9':
nd++
if y.mantCutoffIsUint64Cutoff && r.mantissa < fUint64Cutoff {
r.mantissa *= fBase
xu = r.mantissa + uint64(s[i]-'0')
if xu < r.mantissa {
r.trunc = true
return
}
r.mantissa = xu
} else if r.mantissa < y.mantCutoff {
// mantissa = (mantissa << 1) + (mantissa << 3) + uint64(c-'0')
r.mantissa = r.mantissa*fBase + uint64(s[i]-'0')
} else {
r.trunc = true
return
}
ndMant++
default:
r.bad = true
return
}
}
if !sawdot {
dp = nd
}
if sawexp {
i++
if i < slen {
var eneg bool
if s[i] == '+' {
i++
} else if s[i] == '-' {
i++
eneg = true
}
if i < slen {
// for exact match, exponent is 1 or 2 digits (float64: -22 to 37, float32: -1 to 17).
// exit quick if exponent is more than 2 digits.
if i+2 < slen {
r.hardexp = true
return
}
var e int8
if s[i] < '0' || s[i] > '9' { // !isDigitChar(s[i]) { //
r.bad = true
return
}
e = int8(s[i] - '0')
i++
if i < slen {
if s[i] < '0' || s[i] > '9' { // !isDigitChar(s[i]) { //
r.bad = true
return
}
e = e*fBase + int8(s[i]-'0') // (e << 1) + (e << 3) + int8(s[i]-'0')
i++
}
if eneg {
dp -= e
} else {
dp += e
}
}
}
}
if r.mantissa != 0 {
r.exp = dp - ndMant
// do not set ok=true for cases we cannot handle
if r.exp < -y.exactPow10 ||
r.exp > y.exactInts+y.exactPow10 ||
(y.mantbits != 0 && r.mantissa>>y.mantbits != 0) {
r.hardexp = true
return
}
}
r.ok = true
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/ugorji/go/codec/goversion_growslice_unsafe_lt_go120.go | vendor/github.com/ugorji/go/codec/goversion_growslice_unsafe_lt_go120.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
//go:build go1.9 && !go1.20 && !safe && !codec.safe && !appengine
// +build go1.9,!go1.20,!safe,!codec.safe,!appengine
package codec
import (
_ "runtime" // needed for go linkname(s)
"unsafe"
)
//go:linkname growslice runtime.growslice
//go:noescape
func growslice(typ unsafe.Pointer, old unsafeSlice, num int) unsafeSlice
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ugorji/go/codec/goversion_vendor_eq_go16.go | vendor/github.com/ugorji/go/codec/goversion_vendor_eq_go16.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
//go:build go1.6 && !go1.7
// +build go1.6,!go1.7
package codec
import "os"
var genCheckVendor = os.Getenv("GO15VENDOREXPERIMENT") != "0"
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ugorji/go/codec/helper_unsafe_compiler_not_gc.go | vendor/github.com/ugorji/go/codec/helper_unsafe_compiler_not_gc.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
//go:build !safe && !codec.safe && !appengine && go1.9 && !gc
// +build !safe,!codec.safe,!appengine,go1.9,!gc
package codec
import (
"reflect"
_ "runtime" // needed for go linkname(s)
"unsafe"
)
var unsafeZeroArr [1024]byte
// runtime.growslice does not work with gccgo, failing with "growslice: cap out of range" error.
// consequently, we just call newarray followed by typedslicecopy directly.
func unsafeGrowslice(typ unsafe.Pointer, old unsafeSlice, cap, incr int) (v unsafeSlice) {
size := rtsize2(typ)
if size == 0 {
return unsafeSlice{unsafe.Pointer(&unsafeZeroArr[0]), old.Len, cap + incr}
}
newcap := int(growCap(uint(cap), uint(size), uint(incr)))
v = unsafeSlice{Data: newarray(typ, newcap), Len: old.Len, Cap: newcap}
if old.Len > 0 {
typedslicecopy(typ, v, old)
}
// memmove(v.Data, old.Data, size*uintptr(old.Len))
return
}
// func unsafeNew(t reflect.Type, typ unsafe.Pointer) unsafe.Pointer {
// rv := reflect.New(t)
// return ((*unsafeReflectValue)(unsafe.Pointer(&rv))).ptr
// }
// runtime.{mapassign_fastXXX, mapaccess2_fastXXX} are not supported in gollvm,
// failing with "error: undefined reference" error.
// so we just use runtime.{mapassign, mapaccess2} directly
func mapStoresElemIndirect(elemsize uintptr) bool { return false }
func mapSet(m, k, v reflect.Value, _ mapKeyFastKind, _, valIsRef bool) {
var urv = (*unsafeReflectValue)(unsafe.Pointer(&k))
var kptr = unsafeMapKVPtr(urv)
urv = (*unsafeReflectValue)(unsafe.Pointer(&v))
var vtyp = urv.typ
var vptr = unsafeMapKVPtr(urv)
urv = (*unsafeReflectValue)(unsafe.Pointer(&m))
mptr := rvRefPtr(urv)
vvptr := mapassign(urv.typ, mptr, kptr)
typedmemmove(vtyp, vvptr, vptr)
}
func mapGet(m, k, v reflect.Value, _ mapKeyFastKind, _, valIsRef bool) (_ reflect.Value) {
var urv = (*unsafeReflectValue)(unsafe.Pointer(&k))
var kptr = unsafeMapKVPtr(urv)
urv = (*unsafeReflectValue)(unsafe.Pointer(&m))
mptr := rvRefPtr(urv)
vvptr, ok := mapaccess2(urv.typ, mptr, kptr)
if !ok {
return
}
urv = (*unsafeReflectValue)(unsafe.Pointer(&v))
if helperUnsafeDirectAssignMapEntry || valIsRef {
urv.ptr = vvptr
} else {
typedmemmove(urv.typ, urv.ptr, vvptr)
}
return 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/ugorji/go/codec/goversion_fmt_time_lt_go15.go | vendor/github.com/ugorji/go/codec/goversion_fmt_time_lt_go15.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
//go:build !go1.5
// +build !go1.5
package codec
import "time"
func fmtTime(t time.Time, fmt string, b []byte) []byte {
s := t.Format(fmt)
b = b[:len(s)]
copy(b, s)
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/ugorji/go/codec/register_ext.go | vendor/github.com/ugorji/go/codec/register_ext.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
package codec
import "reflect"
// This file exists, so that the files for specific formats do not all import reflect.
// This just helps us ensure that reflect package is isolated to a few files.
// SetInterfaceExt sets an extension
func (h *JsonHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceExt) (err error) {
return h.SetExt(rt, tag, makeExt(ext))
}
// SetInterfaceExt sets an extension
func (h *CborHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceExt) (err error) {
return h.SetExt(rt, tag, makeExt(ext))
}
// SetBytesExt sets an extension
func (h *MsgpackHandle) SetBytesExt(rt reflect.Type, tag uint64, ext BytesExt) (err error) {
return h.SetExt(rt, tag, makeExt(ext))
}
// SetBytesExt sets an extension
func (h *SimpleHandle) SetBytesExt(rt reflect.Type, tag uint64, ext BytesExt) (err error) {
return h.SetExt(rt, tag, makeExt(ext))
}
// SetBytesExt sets an extension
func (h *BincHandle) SetBytesExt(rt reflect.Type, tag uint64, ext BytesExt) (err error) {
return h.SetExt(rt, tag, makeExt(ext))
}
// func (h *XMLHandle) SetInterfaceExt(rt reflect.Type, tag uint64, ext InterfaceExt) (err error) {
// return h.SetExt(rt, tag, &interfaceExtWrapper{InterfaceExt: ext})
// }
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ugorji/go/codec/goversion_vendor_eq_go15.go | vendor/github.com/ugorji/go/codec/goversion_vendor_eq_go15.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
//go:build go1.5 && !go1.6
// +build go1.5,!go1.6
package codec
import "os"
var genCheckVendor = os.Getenv("GO15VENDOREXPERIMENT") == "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/ugorji/go/codec/rpc.go | vendor/github.com/ugorji/go/codec/rpc.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
package codec
import (
"bufio"
"errors"
"io"
"net/rpc"
)
var (
errRpcIsClosed = errors.New("rpc - connection has been closed")
errRpcNoConn = errors.New("rpc - no connection")
rpcSpaceArr = [1]byte{' '}
)
// Rpc provides a rpc Server or Client Codec for rpc communication.
type Rpc interface {
ServerCodec(conn io.ReadWriteCloser, h Handle) rpc.ServerCodec
ClientCodec(conn io.ReadWriteCloser, h Handle) rpc.ClientCodec
}
// RPCOptions holds options specific to rpc functionality
type RPCOptions struct {
// RPCNoBuffer configures whether we attempt to buffer reads and writes during RPC calls.
//
// Set RPCNoBuffer=true to turn buffering off.
// Buffering can still be done if buffered connections are passed in, or
// buffering is configured on the handle.
RPCNoBuffer bool
}
// rpcCodec defines the struct members and common methods.
type rpcCodec struct {
c io.Closer
r io.Reader
w io.Writer
f ioFlusher
dec *Decoder
enc *Encoder
h Handle
cls atomicClsErr
}
func newRPCCodec(conn io.ReadWriteCloser, h Handle) rpcCodec {
return newRPCCodec2(conn, conn, conn, h)
}
func newRPCCodec2(r io.Reader, w io.Writer, c io.Closer, h Handle) rpcCodec {
bh := h.getBasicHandle()
// if the writer can flush, ensure we leverage it, else
// we may hang waiting on read if write isn't flushed.
// var f ioFlusher
f, ok := w.(ioFlusher)
if !bh.RPCNoBuffer {
if bh.WriterBufferSize <= 0 {
if !ok { // a flusher means there's already a buffer
bw := bufio.NewWriter(w)
f, w = bw, bw
}
}
if bh.ReaderBufferSize <= 0 {
if _, ok = w.(ioBuffered); !ok {
r = bufio.NewReader(r)
}
}
}
return rpcCodec{
c: c,
w: w,
r: r,
f: f,
h: h,
enc: NewEncoder(w, h),
dec: NewDecoder(r, h),
}
}
func (c *rpcCodec) write(obj ...interface{}) (err error) {
err = c.ready()
if err != nil {
return
}
if c.f != nil {
defer func() {
flushErr := c.f.Flush()
if flushErr != nil && err == nil {
err = flushErr
}
}()
}
for _, o := range obj {
err = c.enc.Encode(o)
if err != nil {
return
}
// defensive: ensure a space is always written after each encoding,
// in case the value was a number, and encoding a value right after
// without a space will lead to invalid output.
if c.h.isJson() {
_, err = c.w.Write(rpcSpaceArr[:])
if err != nil {
return
}
}
}
return
}
func (c *rpcCodec) read(obj interface{}) (err error) {
err = c.ready()
if err == nil {
//If nil is passed in, we should read and discard
if obj == nil {
// return c.dec.Decode(&obj)
err = c.dec.swallowErr()
} else {
err = c.dec.Decode(obj)
}
}
return
}
func (c *rpcCodec) Close() (err error) {
if c.c != nil {
cls := c.cls.load()
if !cls.closed {
cls.err = c.c.Close()
cls.closed = true
c.cls.store(cls)
}
err = cls.err
}
return
}
func (c *rpcCodec) ready() (err error) {
if c.c == nil {
err = errRpcNoConn
} else {
cls := c.cls.load()
if cls.closed {
if err = cls.err; err == nil {
err = errRpcIsClosed
}
}
}
return
}
func (c *rpcCodec) ReadResponseBody(body interface{}) error {
return c.read(body)
}
// -------------------------------------
type goRpcCodec struct {
rpcCodec
}
func (c *goRpcCodec) WriteRequest(r *rpc.Request, body interface{}) error {
return c.write(r, body)
}
func (c *goRpcCodec) WriteResponse(r *rpc.Response, body interface{}) error {
return c.write(r, body)
}
func (c *goRpcCodec) ReadResponseHeader(r *rpc.Response) error {
return c.read(r)
}
func (c *goRpcCodec) ReadRequestHeader(r *rpc.Request) error {
return c.read(r)
}
func (c *goRpcCodec) ReadRequestBody(body interface{}) error {
return c.read(body)
}
// -------------------------------------
// goRpc is the implementation of Rpc that uses the communication protocol
// as defined in net/rpc package.
type goRpc struct{}
// GoRpc implements Rpc using the communication protocol defined in net/rpc package.
//
// Note: network connection (from net.Dial, of type io.ReadWriteCloser) is not buffered.
//
// For performance, you should configure WriterBufferSize and ReaderBufferSize on the handle.
// This ensures we use an adequate buffer during reading and writing.
// If not configured, we will internally initialize and use a buffer during reads and writes.
// This can be turned off via the RPCNoBuffer option on the Handle.
//
// var handle codec.JsonHandle
// handle.RPCNoBuffer = true // turns off attempt by rpc module to initialize a buffer
//
// Example 1: one way of configuring buffering explicitly:
//
// var handle codec.JsonHandle // codec handle
// handle.ReaderBufferSize = 1024
// handle.WriterBufferSize = 1024
// var conn io.ReadWriteCloser // connection got from a socket
// var serverCodec = GoRpc.ServerCodec(conn, handle)
// var clientCodec = GoRpc.ClientCodec(conn, handle)
//
// Example 2: you can also explicitly create a buffered connection yourself,
// and not worry about configuring the buffer sizes in the Handle.
//
// var handle codec.Handle // codec handle
// var conn io.ReadWriteCloser // connection got from a socket
// var bufconn = struct { // bufconn here is a buffered io.ReadWriteCloser
// io.Closer
// *bufio.Reader
// *bufio.Writer
// }{conn, bufio.NewReader(conn), bufio.NewWriter(conn)}
// var serverCodec = GoRpc.ServerCodec(bufconn, handle)
// var clientCodec = GoRpc.ClientCodec(bufconn, handle)
var GoRpc goRpc
func (x goRpc) ServerCodec(conn io.ReadWriteCloser, h Handle) rpc.ServerCodec {
return &goRpcCodec{newRPCCodec(conn, h)}
}
func (x goRpc) ClientCodec(conn io.ReadWriteCloser, h Handle) rpc.ClientCodec {
return &goRpcCodec{newRPCCodec(conn, h)}
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ugorji/go/codec/cbor.go | vendor/github.com/ugorji/go/codec/cbor.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
package codec
import (
"math"
"reflect"
"time"
"unicode/utf8"
)
// major
const (
cborMajorUint byte = iota
cborMajorNegInt
cborMajorBytes
cborMajorString
cborMajorArray
cborMajorMap
cborMajorTag
cborMajorSimpleOrFloat
)
// simple
const (
cborBdFalse byte = 0xf4 + iota
cborBdTrue
cborBdNil
cborBdUndefined
cborBdExt
cborBdFloat16
cborBdFloat32
cborBdFloat64
)
// indefinite
const (
cborBdIndefiniteBytes byte = 0x5f
cborBdIndefiniteString byte = 0x7f
cborBdIndefiniteArray byte = 0x9f
cborBdIndefiniteMap byte = 0xbf
cborBdBreak byte = 0xff
)
// These define some in-stream descriptors for
// manual encoding e.g. when doing explicit indefinite-length
const (
CborStreamBytes byte = 0x5f
CborStreamString byte = 0x7f
CborStreamArray byte = 0x9f
CborStreamMap byte = 0xbf
CborStreamBreak byte = 0xff
)
// base values
const (
cborBaseUint byte = 0x00
cborBaseNegInt byte = 0x20
cborBaseBytes byte = 0x40
cborBaseString byte = 0x60
cborBaseArray byte = 0x80
cborBaseMap byte = 0xa0
cborBaseTag byte = 0xc0
cborBaseSimple byte = 0xe0
)
// const (
// cborSelfDesrTag byte = 0xd9
// cborSelfDesrTag2 byte = 0xd9
// cborSelfDesrTag3 byte = 0xf7
// )
var (
cbordescSimpleNames = map[byte]string{
cborBdNil: "nil",
cborBdFalse: "false",
cborBdTrue: "true",
cborBdFloat16: "float",
cborBdFloat32: "float",
cborBdFloat64: "float",
cborBdBreak: "break",
}
cbordescIndefNames = map[byte]string{
cborBdIndefiniteBytes: "bytes*",
cborBdIndefiniteString: "string*",
cborBdIndefiniteArray: "array*",
cborBdIndefiniteMap: "map*",
}
cbordescMajorNames = map[byte]string{
cborMajorUint: "(u)int",
cborMajorNegInt: "int",
cborMajorBytes: "bytes",
cborMajorString: "string",
cborMajorArray: "array",
cborMajorMap: "map",
cborMajorTag: "tag",
cborMajorSimpleOrFloat: "simple",
}
)
func cbordesc(bd byte) (s string) {
bm := bd >> 5
if bm == cborMajorSimpleOrFloat {
s = cbordescSimpleNames[bd]
} else {
s = cbordescMajorNames[bm]
if s == "" {
s = cbordescIndefNames[bd]
}
}
if s == "" {
s = "unknown"
}
return
}
// -------------------
type cborEncDriver struct {
noBuiltInTypes
encDriverNoState
encDriverNoopContainerWriter
h *CborHandle
// scratch buffer for: encode time, numbers, etc
//
// RFC3339Nano uses 35 chars: 2006-01-02T15:04:05.999999999Z07:00
b [40]byte
e Encoder
}
func (e *cborEncDriver) encoder() *Encoder {
return &e.e
}
func (e *cborEncDriver) EncodeNil() {
e.e.encWr.writen1(cborBdNil)
}
func (e *cborEncDriver) EncodeBool(b bool) {
if b {
e.e.encWr.writen1(cborBdTrue)
} else {
e.e.encWr.writen1(cborBdFalse)
}
}
func (e *cborEncDriver) EncodeFloat32(f float32) {
b := math.Float32bits(f)
if e.h.OptimumSize {
if h := floatToHalfFloatBits(b); halfFloatToFloatBits(h) == b {
e.e.encWr.writen1(cborBdFloat16)
bigen.writeUint16(e.e.w(), h)
return
}
}
e.e.encWr.writen1(cborBdFloat32)
bigen.writeUint32(e.e.w(), b)
}
func (e *cborEncDriver) EncodeFloat64(f float64) {
if e.h.OptimumSize {
if f32 := float32(f); float64(f32) == f {
e.EncodeFloat32(f32)
return
}
}
e.e.encWr.writen1(cborBdFloat64)
bigen.writeUint64(e.e.w(), math.Float64bits(f))
}
func (e *cborEncDriver) encUint(v uint64, bd byte) {
if v <= 0x17 {
e.e.encWr.writen1(byte(v) + bd)
} else if v <= math.MaxUint8 {
e.e.encWr.writen2(bd+0x18, uint8(v))
} else if v <= math.MaxUint16 {
e.e.encWr.writen1(bd + 0x19)
bigen.writeUint16(e.e.w(), uint16(v))
} else if v <= math.MaxUint32 {
e.e.encWr.writen1(bd + 0x1a)
bigen.writeUint32(e.e.w(), uint32(v))
} else { // if v <= math.MaxUint64 {
e.e.encWr.writen1(bd + 0x1b)
bigen.writeUint64(e.e.w(), v)
}
}
func (e *cborEncDriver) EncodeInt(v int64) {
if v < 0 {
e.encUint(uint64(-1-v), cborBaseNegInt)
} else {
e.encUint(uint64(v), cborBaseUint)
}
}
func (e *cborEncDriver) EncodeUint(v uint64) {
e.encUint(v, cborBaseUint)
}
func (e *cborEncDriver) encLen(bd byte, length int) {
e.encUint(uint64(length), bd)
}
func (e *cborEncDriver) EncodeTime(t time.Time) {
if t.IsZero() {
e.EncodeNil()
} else if e.h.TimeRFC3339 {
e.encUint(0, cborBaseTag)
e.encStringBytesS(cborBaseString, stringView(fmtTime(t, time.RFC3339Nano, e.b[:0])))
} else {
e.encUint(1, cborBaseTag)
t = t.UTC().Round(time.Microsecond)
sec, nsec := t.Unix(), uint64(t.Nanosecond())
if nsec == 0 {
e.EncodeInt(sec)
} else {
e.EncodeFloat64(float64(sec) + float64(nsec)/1e9)
}
}
}
func (e *cborEncDriver) EncodeExt(rv interface{}, basetype reflect.Type, xtag uint64, ext Ext) {
e.encUint(uint64(xtag), cborBaseTag)
if ext == SelfExt {
e.e.encodeValue(baseRV(rv), e.h.fnNoExt(basetype))
} else if v := ext.ConvertExt(rv); v == nil {
e.EncodeNil()
} else {
e.e.encode(v)
}
}
func (e *cborEncDriver) EncodeRawExt(re *RawExt) {
e.encUint(uint64(re.Tag), cborBaseTag)
// only encodes re.Value (never re.Data)
if re.Value != nil {
e.e.encode(re.Value)
} else {
e.EncodeNil()
}
}
func (e *cborEncDriver) WriteArrayStart(length int) {
if e.h.IndefiniteLength {
e.e.encWr.writen1(cborBdIndefiniteArray)
} else {
e.encLen(cborBaseArray, length)
}
}
func (e *cborEncDriver) WriteMapStart(length int) {
if e.h.IndefiniteLength {
e.e.encWr.writen1(cborBdIndefiniteMap)
} else {
e.encLen(cborBaseMap, length)
}
}
func (e *cborEncDriver) WriteMapEnd() {
if e.h.IndefiniteLength {
e.e.encWr.writen1(cborBdBreak)
}
}
func (e *cborEncDriver) WriteArrayEnd() {
if e.h.IndefiniteLength {
e.e.encWr.writen1(cborBdBreak)
}
}
func (e *cborEncDriver) EncodeString(v string) {
bb := cborBaseString
if e.h.StringToRaw {
bb = cborBaseBytes
}
e.encStringBytesS(bb, v)
}
func (e *cborEncDriver) EncodeStringBytesRaw(v []byte) {
if v == nil {
e.EncodeNil()
} else {
e.encStringBytesS(cborBaseBytes, stringView(v))
}
}
func (e *cborEncDriver) encStringBytesS(bb byte, v string) {
if e.h.IndefiniteLength {
if bb == cborBaseBytes {
e.e.encWr.writen1(cborBdIndefiniteBytes)
} else {
e.e.encWr.writen1(cborBdIndefiniteString)
}
var vlen uint = uint(len(v))
blen := vlen / 4
if blen == 0 {
blen = 64
} else if blen > 1024 {
blen = 1024
}
for i := uint(0); i < vlen; {
var v2 string
i2 := i + blen
if i2 >= i && i2 < vlen {
v2 = v[i:i2]
} else {
v2 = v[i:]
}
e.encLen(bb, len(v2))
e.e.encWr.writestr(v2)
i = i2
}
e.e.encWr.writen1(cborBdBreak)
} else {
e.encLen(bb, len(v))
e.e.encWr.writestr(v)
}
}
// ----------------------
type cborDecDriver struct {
decDriverNoopContainerReader
decDriverNoopNumberHelper
h *CborHandle
bdAndBdread
st bool // skip tags
_ bool // found nil
noBuiltInTypes
d Decoder
}
func (d *cborDecDriver) decoder() *Decoder {
return &d.d
}
func (d *cborDecDriver) descBd() string {
return sprintf("%v (%s)", d.bd, cbordesc(d.bd))
}
func (d *cborDecDriver) readNextBd() {
d.bd = d.d.decRd.readn1()
d.bdRead = true
}
func (d *cborDecDriver) advanceNil() (null bool) {
if !d.bdRead {
d.readNextBd()
}
if d.bd == cborBdNil || d.bd == cborBdUndefined {
d.bdRead = false
return true // null = true
}
return
}
func (d *cborDecDriver) TryNil() bool {
return d.advanceNil()
}
// skipTags is called to skip any tags in the stream.
//
// Since any value can be tagged, then we should call skipTags
// before any value is decoded.
//
// By definition, skipTags should not be called before
// checking for break, or nil or undefined.
func (d *cborDecDriver) skipTags() {
for d.bd>>5 == cborMajorTag {
d.decUint()
d.bd = d.d.decRd.readn1()
}
}
func (d *cborDecDriver) ContainerType() (vt valueType) {
if !d.bdRead {
d.readNextBd()
}
if d.st {
d.skipTags()
}
if d.bd == cborBdNil {
d.bdRead = false // always consume nil after seeing it in container type
return valueTypeNil
}
major := d.bd >> 5
if major == cborMajorBytes {
return valueTypeBytes
} else if major == cborMajorString {
return valueTypeString
} else if major == cborMajorArray {
return valueTypeArray
} else if major == cborMajorMap {
return valueTypeMap
}
return valueTypeUnset
}
func (d *cborDecDriver) CheckBreak() (v bool) {
if !d.bdRead {
d.readNextBd()
}
if d.bd == cborBdBreak {
d.bdRead = false
v = true
}
return
}
func (d *cborDecDriver) decUint() (ui uint64) {
v := d.bd & 0x1f
if v <= 0x17 {
ui = uint64(v)
} else if v == 0x18 {
ui = uint64(d.d.decRd.readn1())
} else if v == 0x19 {
ui = uint64(bigen.Uint16(d.d.decRd.readn2()))
} else if v == 0x1a {
ui = uint64(bigen.Uint32(d.d.decRd.readn4()))
} else if v == 0x1b {
ui = uint64(bigen.Uint64(d.d.decRd.readn8()))
} else {
d.d.errorf("invalid descriptor decoding uint: %x/%s", d.bd, cbordesc(d.bd))
}
return
}
func (d *cborDecDriver) decLen() int {
return int(d.decUint())
}
func (d *cborDecDriver) decAppendIndefiniteBytes(bs []byte, major byte) []byte {
d.bdRead = false
for !d.CheckBreak() {
chunkMajor := d.bd >> 5
if chunkMajor != major {
d.d.errorf("malformed indefinite string/bytes %x (%s); contains chunk with major type %v, expected %v",
d.bd, cbordesc(d.bd), chunkMajor, major)
}
n := uint(d.decLen())
oldLen := uint(len(bs))
newLen := oldLen + n
if newLen > uint(cap(bs)) {
bs2 := make([]byte, newLen, 2*uint(cap(bs))+n)
copy(bs2, bs)
bs = bs2
} else {
bs = bs[:newLen]
}
d.d.decRd.readb(bs[oldLen:newLen])
if d.h.ValidateUnicode && major == cborMajorString && !utf8.Valid(bs[oldLen:newLen]) {
d.d.errorf("indefinite-length text string contains chunk that is not a valid utf-8 sequence: 0x%x", bs[oldLen:newLen])
}
d.bdRead = false
}
d.bdRead = false
return bs
}
func (d *cborDecDriver) decFloat() (f float64, ok bool) {
ok = true
switch d.bd {
case cborBdFloat16:
f = float64(math.Float32frombits(halfFloatToFloatBits(bigen.Uint16(d.d.decRd.readn2()))))
case cborBdFloat32:
f = float64(math.Float32frombits(bigen.Uint32(d.d.decRd.readn4())))
case cborBdFloat64:
f = math.Float64frombits(bigen.Uint64(d.d.decRd.readn8()))
default:
ok = false
}
return
}
func (d *cborDecDriver) decInteger() (ui uint64, neg, ok bool) {
ok = true
switch d.bd >> 5 {
case cborMajorUint:
ui = d.decUint()
case cborMajorNegInt:
ui = d.decUint()
neg = true
default:
ok = false
}
return
}
func (d *cborDecDriver) DecodeInt64() (i int64) {
if d.advanceNil() {
return
}
if d.st {
d.skipTags()
}
i = decNegintPosintFloatNumberHelper{&d.d}.int64(d.decInteger())
d.bdRead = false
return
}
func (d *cborDecDriver) DecodeUint64() (ui uint64) {
if d.advanceNil() {
return
}
if d.st {
d.skipTags()
}
ui = decNegintPosintFloatNumberHelper{&d.d}.uint64(d.decInteger())
d.bdRead = false
return
}
func (d *cborDecDriver) DecodeFloat64() (f float64) {
if d.advanceNil() {
return
}
if d.st {
d.skipTags()
}
f = decNegintPosintFloatNumberHelper{&d.d}.float64(d.decFloat())
d.bdRead = false
return
}
// bool can be decoded from bool only (single byte).
func (d *cborDecDriver) DecodeBool() (b bool) {
if d.advanceNil() {
return
}
if d.st {
d.skipTags()
}
if d.bd == cborBdTrue {
b = true
} else if d.bd == cborBdFalse {
} else {
d.d.errorf("not bool - %s %x/%s", msgBadDesc, d.bd, cbordesc(d.bd))
}
d.bdRead = false
return
}
func (d *cborDecDriver) ReadMapStart() (length int) {
if d.advanceNil() {
return containerLenNil
}
if d.st {
d.skipTags()
}
d.bdRead = false
if d.bd == cborBdIndefiniteMap {
return containerLenUnknown
}
if d.bd>>5 != cborMajorMap {
d.d.errorf("error reading map; got major type: %x, expected %x/%s", d.bd>>5, cborMajorMap, cbordesc(d.bd))
}
return d.decLen()
}
func (d *cborDecDriver) ReadArrayStart() (length int) {
if d.advanceNil() {
return containerLenNil
}
if d.st {
d.skipTags()
}
d.bdRead = false
if d.bd == cborBdIndefiniteArray {
return containerLenUnknown
}
if d.bd>>5 != cborMajorArray {
d.d.errorf("invalid array; got major type: %x, expect: %x/%s", d.bd>>5, cborMajorArray, cbordesc(d.bd))
}
return d.decLen()
}
func (d *cborDecDriver) DecodeBytes(bs []byte) (bsOut []byte) {
d.d.decByteState = decByteStateNone
if d.advanceNil() {
return
}
if d.st {
d.skipTags()
}
if d.bd == cborBdIndefiniteBytes || d.bd == cborBdIndefiniteString {
d.bdRead = false
if bs == nil {
d.d.decByteState = decByteStateReuseBuf
return d.decAppendIndefiniteBytes(d.d.b[:0], d.bd>>5)
}
return d.decAppendIndefiniteBytes(bs[:0], d.bd>>5)
}
if d.bd == cborBdIndefiniteArray {
d.bdRead = false
if bs == nil {
d.d.decByteState = decByteStateReuseBuf
bs = d.d.b[:0]
} else {
bs = bs[:0]
}
for !d.CheckBreak() {
bs = append(bs, uint8(chkOvf.UintV(d.DecodeUint64(), 8)))
}
return bs
}
if d.bd>>5 == cborMajorArray {
d.bdRead = false
if bs == nil {
d.d.decByteState = decByteStateReuseBuf
bs = d.d.b[:]
}
slen := d.decLen()
var changed bool
if bs, changed = usableByteSlice(bs, slen); changed {
d.d.decByteState = decByteStateNone
}
for i := 0; i < len(bs); i++ {
bs[i] = uint8(chkOvf.UintV(d.DecodeUint64(), 8))
}
for i := len(bs); i < slen; i++ {
bs = append(bs, uint8(chkOvf.UintV(d.DecodeUint64(), 8)))
}
return bs
}
clen := d.decLen()
d.bdRead = false
if d.d.zerocopy() {
d.d.decByteState = decByteStateZerocopy
return d.d.decRd.rb.readx(uint(clen))
}
if bs == nil {
d.d.decByteState = decByteStateReuseBuf
bs = d.d.b[:]
}
return decByteSlice(d.d.r(), clen, d.h.MaxInitLen, bs)
}
func (d *cborDecDriver) DecodeStringAsBytes() (s []byte) {
s = d.DecodeBytes(nil)
if d.h.ValidateUnicode && !utf8.Valid(s) {
d.d.errorf("DecodeStringAsBytes: invalid UTF-8: %s", s)
}
return
}
func (d *cborDecDriver) DecodeTime() (t time.Time) {
if d.advanceNil() {
return
}
if d.bd>>5 != cborMajorTag {
d.d.errorf("error reading tag; expected major type: %x, got: %x", cborMajorTag, d.bd>>5)
}
xtag := d.decUint()
d.bdRead = false
return d.decodeTime(xtag)
}
func (d *cborDecDriver) decodeTime(xtag uint64) (t time.Time) {
switch xtag {
case 0:
var err error
t, err = time.Parse(time.RFC3339, stringView(d.DecodeStringAsBytes()))
d.d.onerror(err)
case 1:
f1, f2 := math.Modf(d.DecodeFloat64())
t = time.Unix(int64(f1), int64(f2*1e9))
default:
d.d.errorf("invalid tag for time.Time - expecting 0 or 1, got 0x%x", xtag)
}
t = t.UTC().Round(time.Microsecond)
return
}
func (d *cborDecDriver) DecodeExt(rv interface{}, basetype reflect.Type, xtag uint64, ext Ext) {
if d.advanceNil() {
return
}
if d.bd>>5 != cborMajorTag {
d.d.errorf("error reading tag; expected major type: %x, got: %x", cborMajorTag, d.bd>>5)
}
realxtag := d.decUint()
d.bdRead = false
if ext == nil {
re := rv.(*RawExt)
re.Tag = realxtag
d.d.decode(&re.Value)
} else if xtag != realxtag {
d.d.errorf("Wrong extension tag. Got %b. Expecting: %v", realxtag, xtag)
} else if ext == SelfExt {
d.d.decodeValue(baseRV(rv), d.h.fnNoExt(basetype))
} else {
d.d.interfaceExtConvertAndDecode(rv, ext)
}
d.bdRead = false
}
func (d *cborDecDriver) DecodeNaked() {
if !d.bdRead {
d.readNextBd()
}
n := d.d.naked()
var decodeFurther bool
switch d.bd >> 5 {
case cborMajorUint:
if d.h.SignedInteger {
n.v = valueTypeInt
n.i = d.DecodeInt64()
} else {
n.v = valueTypeUint
n.u = d.DecodeUint64()
}
case cborMajorNegInt:
n.v = valueTypeInt
n.i = d.DecodeInt64()
case cborMajorBytes:
d.d.fauxUnionReadRawBytes(false)
case cborMajorString:
n.v = valueTypeString
n.s = d.d.stringZC(d.DecodeStringAsBytes())
case cborMajorArray:
n.v = valueTypeArray
decodeFurther = true
case cborMajorMap:
n.v = valueTypeMap
decodeFurther = true
case cborMajorTag:
n.v = valueTypeExt
n.u = d.decUint()
n.l = nil
if n.u == 0 || n.u == 1 {
d.bdRead = false
n.v = valueTypeTime
n.t = d.decodeTime(n.u)
} else if d.st && d.h.getExtForTag(n.u) == nil {
// d.skipTags() // no need to call this - tags already skipped
d.bdRead = false
d.DecodeNaked()
return // return when done (as true recursive function)
}
case cborMajorSimpleOrFloat:
switch d.bd {
case cborBdNil, cborBdUndefined:
n.v = valueTypeNil
case cborBdFalse:
n.v = valueTypeBool
n.b = false
case cborBdTrue:
n.v = valueTypeBool
n.b = true
case cborBdFloat16, cborBdFloat32, cborBdFloat64:
n.v = valueTypeFloat
n.f = d.DecodeFloat64()
default:
d.d.errorf("decodeNaked: Unrecognized d.bd: 0x%x", d.bd)
}
default: // should never happen
d.d.errorf("decodeNaked: Unrecognized d.bd: 0x%x", d.bd)
}
if !decodeFurther {
d.bdRead = false
}
}
func (d *cborDecDriver) uintBytes() (v []byte, ui uint64) {
// this is only used by nextValueBytes, so it's ok to
// use readx and bigenstd here.
switch vv := d.bd & 0x1f; vv {
case 0x18:
v = d.d.decRd.readx(1)
ui = uint64(v[0])
case 0x19:
v = d.d.decRd.readx(2)
ui = uint64(bigenstd.Uint16(v))
case 0x1a:
v = d.d.decRd.readx(4)
ui = uint64(bigenstd.Uint32(v))
case 0x1b:
v = d.d.decRd.readx(8)
ui = uint64(bigenstd.Uint64(v))
default:
if vv > 0x1b {
d.d.errorf("invalid descriptor decoding uint: %x/%s", d.bd, cbordesc(d.bd))
}
ui = uint64(vv)
}
return
}
func (d *cborDecDriver) nextValueBytes(v0 []byte) (v []byte) {
if !d.bdRead {
d.readNextBd()
}
v = v0
var h = decNextValueBytesHelper{d: &d.d}
var cursor = d.d.rb.c - 1
h.append1(&v, d.bd)
v = d.nextValueBytesBdReadR(v)
d.bdRead = false
h.bytesRdV(&v, cursor)
return
}
func (d *cborDecDriver) nextValueBytesR(v0 []byte) (v []byte) {
d.readNextBd()
v = v0
var h = decNextValueBytesHelper{d: &d.d}
h.append1(&v, d.bd)
return d.nextValueBytesBdReadR(v)
}
func (d *cborDecDriver) nextValueBytesBdReadR(v0 []byte) (v []byte) {
v = v0
var h = decNextValueBytesHelper{d: &d.d}
var bs []byte
var ui uint64
switch d.bd >> 5 {
case cborMajorUint, cborMajorNegInt:
bs, _ = d.uintBytes()
h.appendN(&v, bs...)
case cborMajorString, cborMajorBytes:
if d.bd == cborBdIndefiniteBytes || d.bd == cborBdIndefiniteString {
for {
d.readNextBd()
h.append1(&v, d.bd)
if d.bd == cborBdBreak {
break
}
bs, ui = d.uintBytes()
h.appendN(&v, bs...)
h.appendN(&v, d.d.decRd.readx(uint(ui))...)
}
} else {
bs, ui = d.uintBytes()
h.appendN(&v, bs...)
h.appendN(&v, d.d.decRd.readx(uint(ui))...)
}
case cborMajorArray:
if d.bd == cborBdIndefiniteArray {
for {
d.readNextBd()
h.append1(&v, d.bd)
if d.bd == cborBdBreak {
break
}
v = d.nextValueBytesBdReadR(v)
}
} else {
bs, ui = d.uintBytes()
h.appendN(&v, bs...)
for i := uint64(0); i < ui; i++ {
v = d.nextValueBytesR(v)
}
}
case cborMajorMap:
if d.bd == cborBdIndefiniteMap {
for {
d.readNextBd()
h.append1(&v, d.bd)
if d.bd == cborBdBreak {
break
}
v = d.nextValueBytesBdReadR(v)
v = d.nextValueBytesR(v)
}
} else {
bs, ui = d.uintBytes()
h.appendN(&v, bs...)
for i := uint64(0); i < ui; i++ {
v = d.nextValueBytesR(v)
v = d.nextValueBytesR(v)
}
}
case cborMajorTag:
bs, _ = d.uintBytes()
h.appendN(&v, bs...)
v = d.nextValueBytesR(v)
case cborMajorSimpleOrFloat:
switch d.bd {
case cborBdNil, cborBdUndefined, cborBdFalse, cborBdTrue: // pass
case cborBdFloat16:
h.appendN(&v, d.d.decRd.readx(2)...)
case cborBdFloat32:
h.appendN(&v, d.d.decRd.readx(4)...)
case cborBdFloat64:
h.appendN(&v, d.d.decRd.readx(8)...)
default:
d.d.errorf("nextValueBytes: Unrecognized d.bd: 0x%x", d.bd)
}
default: // should never happen
d.d.errorf("nextValueBytes: Unrecognized d.bd: 0x%x", d.bd)
}
return
}
// -------------------------
// CborHandle is a Handle for the CBOR encoding format,
// defined at http://tools.ietf.org/html/rfc7049 and documented further at http://cbor.io .
//
// CBOR is comprehensively supported, including support for:
// - indefinite-length arrays/maps/bytes/strings
// - (extension) tags in range 0..0xffff (0 .. 65535)
// - half, single and double-precision floats
// - all numbers (1, 2, 4 and 8-byte signed and unsigned integers)
// - nil, true, false, ...
// - arrays and maps, bytes and text strings
//
// None of the optional extensions (with tags) defined in the spec are supported out-of-the-box.
// Users can implement them as needed (using SetExt), including spec-documented ones:
// - timestamp, BigNum, BigFloat, Decimals,
// - Encoded Text (e.g. URL, regexp, base64, MIME Message), etc.
type CborHandle struct {
binaryEncodingType
// noElemSeparators
BasicHandle
// IndefiniteLength=true, means that we encode using indefinitelength
IndefiniteLength bool
// TimeRFC3339 says to encode time.Time using RFC3339 format.
// If unset, we encode time.Time using seconds past epoch.
TimeRFC3339 bool
// SkipUnexpectedTags says to skip over any tags for which extensions are
// not defined. This is in keeping with the cbor spec on "Optional Tagging of Items".
//
// Furthermore, this allows the skipping over of the Self Describing Tag 0xd9d9f7.
SkipUnexpectedTags bool
}
// Name returns the name of the handle: cbor
func (h *CborHandle) Name() string { return "cbor" }
func (h *CborHandle) desc(bd byte) string { return cbordesc(bd) }
func (h *CborHandle) newEncDriver() encDriver {
var e = &cborEncDriver{h: h}
e.e.e = e
e.e.init(h)
e.reset()
return e
}
func (h *CborHandle) newDecDriver() decDriver {
d := &cborDecDriver{h: h, st: h.SkipUnexpectedTags}
d.d.d = d
d.d.cbor = true
d.d.init(h)
d.reset()
return d
}
func (d *cborDecDriver) reset() {
d.bdAndBdread.reset()
d.st = d.h.SkipUnexpectedTags
}
var _ decDriver = (*cborDecDriver)(nil)
var _ encDriver = (*cborEncDriver)(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/ugorji/go/codec/helper.go | vendor/github.com/ugorji/go/codec/helper.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
package codec
// Contains code shared by both encode and decode.
// Some shared ideas around encoding/decoding
// ------------------------------------------
//
// If an interface{} is passed, we first do a type assertion to see if it is
// a primitive type or a map/slice of primitive types, and use a fastpath to handle it.
//
// If we start with a reflect.Value, we are already in reflect.Value land and
// will try to grab the function for the underlying Type and directly call that function.
// This is more performant than calling reflect.Value.Interface().
//
// This still helps us bypass many layers of reflection, and give best performance.
//
// Containers
// ------------
// Containers in the stream are either associative arrays (key-value pairs) or
// regular arrays (indexed by incrementing integers).
//
// Some streams support indefinite-length containers, and use a breaking
// byte-sequence to denote that the container has come to an end.
//
// Some streams also are text-based, and use explicit separators to denote the
// end/beginning of different values.
//
// Philosophy
// ------------
// On decode, this codec will update containers appropriately:
// - If struct, update fields from stream into fields of struct.
// If field in stream not found in struct, handle appropriately (based on option).
// If a struct field has no corresponding value in the stream, leave it AS IS.
// If nil in stream, set value to nil/zero value.
// - If map, update map from stream.
// If the stream value is NIL, set the map to nil.
// - if slice, try to update up to length of array in stream.
// if container len is less than stream array length,
// and container cannot be expanded, handled (based on option).
// This means you can decode 4-element stream array into 1-element array.
//
// ------------------------------------
// On encode, user can specify omitEmpty. This means that the value will be omitted
// if the zero value. The problem may occur during decode, where omitted values do not affect
// the value being decoded into. This means that if decoding into a struct with an
// int field with current value=5, and the field is omitted in the stream, then after
// decoding, the value will still be 5 (not 0).
// omitEmpty only works if you guarantee that you always decode into zero-values.
//
// ------------------------------------
// We could have truncated a map to remove keys not available in the stream,
// or set values in the struct which are not in the stream to their zero values.
// We decided against it because there is no efficient way to do it.
// We may introduce it as an option later.
// However, that will require enabling it for both runtime and code generation modes.
//
// To support truncate, we need to do 2 passes over the container:
// map
// - first collect all keys (e.g. in k1)
// - for each key in stream, mark k1 that the key should not be removed
// - after updating map, do second pass and call delete for all keys in k1 which are not marked
// struct:
// - for each field, track the *typeInfo s1
// - iterate through all s1, and for each one not marked, set value to zero
// - this involves checking the possible anonymous fields which are nil ptrs.
// too much work.
//
// ------------------------------------------
// Error Handling is done within the library using panic.
//
// This way, the code doesn't have to keep checking if an error has happened,
// and we don't have to keep sending the error value along with each call
// or storing it in the En|Decoder and checking it constantly along the way.
//
// We considered storing the error is En|Decoder.
// - once it has its err field set, it cannot be used again.
// - panicing will be optional, controlled by const flag.
// - code should always check error first and return early.
//
// We eventually decided against it as it makes the code clumsier to always
// check for these error conditions.
//
// ------------------------------------------
// We use sync.Pool only for the aid of long-lived objects shared across multiple goroutines.
// Encoder, Decoder, enc|decDriver, reader|writer, etc do not fall into this bucket.
//
// Also, GC is much better now, eliminating some of the reasons to use a shared pool structure.
// Instead, the short-lived objects use free-lists that live as long as the object exists.
//
// ------------------------------------------
// Performance is affected by the following:
// - Bounds Checking
// - Inlining
// - Pointer chasing
// This package tries hard to manage the performance impact of these.
//
// ------------------------------------------
// To alleviate performance due to pointer-chasing:
// - Prefer non-pointer values in a struct field
// - Refer to these directly within helper classes
// e.g. json.go refers directly to d.d.decRd
//
// We made the changes to embed En/Decoder in en/decDriver,
// but we had to explicitly reference the fields as opposed to using a function
// to get the better performance that we were looking for.
// For example, we explicitly call d.d.decRd.fn() instead of d.d.r().fn().
//
// ------------------------------------------
// Bounds Checking
// - Allow bytesDecReader to incur "bounds check error", and recover that as an io error.
// This allows the bounds check branch to always be taken by the branch predictor,
// giving better performance (in theory), while ensuring that the code is shorter.
//
// ------------------------------------------
// Escape Analysis
// - Prefer to return non-pointers if the value is used right away.
// Newly allocated values returned as pointers will be heap-allocated as they escape.
//
// Prefer functions and methods that
// - take no parameters and
// - return no results and
// - do not allocate.
// These are optimized by the runtime.
// For example, in json, we have dedicated functions for ReadMapElemKey, etc
// which do not delegate to readDelim, as readDelim takes a parameter.
// The difference in runtime was as much as 5%.
//
// ------------------------------------------
// Handling Nil
// - In dynamic (reflection) mode, decodeValue and encodeValue handle nil at the top
// - Consequently, methods used with them as a parent in the chain e.g. kXXX
// methods do not handle nil.
// - Fastpath methods also do not handle nil.
// The switch called in (en|de)code(...) handles it so the dependent calls don't have to.
// - codecgen will handle nil before calling into the library for further work also.
//
// ------------------------------------------
// Passing reflect.Kind to functions that take a reflect.Value
// - Note that reflect.Value.Kind() is very cheap, as its fundamentally a binary AND of 2 numbers
//
// ------------------------------------------
// Transient values during decoding
//
// With reflection, the stack is not used. Consequently, values which may be stack-allocated in
// normal use will cause a heap allocation when using reflection.
//
// There are cases where we know that a value is transient, and we just need to decode into it
// temporarily so we can right away use its value for something else.
//
// In these situations, we can elide the heap allocation by being deliberate with use of a pre-cached
// scratch memory or scratch value.
//
// We use this for situations:
// - decode into a temp value x, and then set x into an interface
// - decode into a temp value, for use as a map key, to lookup up a map value
// - decode into a temp value, for use as a map value, to set into a map
// - decode into a temp value, for sending into a channel
//
// By definition, Transient values are NEVER pointer-shaped values,
// like pointer, func, map, chan. Using transient for pointer-shaped values
// can lead to data corruption when GC tries to follow what it saw as a pointer at one point.
//
// In general, transient values are values which can be decoded as an atomic value
// using a single call to the decDriver. This naturally includes bool or numeric types.
//
// Note that some values which "contain" pointers, specifically string and slice,
// can also be transient. In the case of string, it is decoded as an atomic value.
// In the case of a slice, decoding into its elements always uses an addressable
// value in memory ie we grow the slice, and then decode directly into the memory
// address corresponding to that index in the slice.
//
// To handle these string and slice values, we have to use a scratch value
// which has the same shape of a string or slice.
//
// Consequently, the full range of types which can be transient is:
// - numbers
// - bool
// - string
// - slice
//
// and whbut we MUST use a scratch space with that element
// being defined as an unsafe.Pointer to start with.
//
// We have to be careful with maps. Because we iterate map keys and values during a range,
// we must have 2 variants of the scratch space/value for maps and keys separately.
//
// These are the TransientAddrK and TransientAddr2K methods of decPerType.
import (
"encoding"
"encoding/binary"
"errors"
"fmt"
"io"
"math"
"reflect"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unicode/utf8"
)
// if debugging is true, then
// - within Encode/Decode, do not recover from panic's
// - etc
//
// Note: Negative tests that check for errors will fail, so only use this
// when debugging, and run only one test at a time preferably.
//
// Note: RPC tests depend on getting the error from an Encode/Decode call.
// Consequently, they will always fail if debugging = true.
const debugging = false
const (
// containerLenUnknown is length returned from Read(Map|Array)Len
// when a format doesn't know apiori.
// For example, json doesn't pre-determine the length of a container (sequence/map).
containerLenUnknown = -1
// containerLenNil is length returned from Read(Map|Array)Len
// when a 'nil' was encountered in the stream.
containerLenNil = math.MinInt32
// [N]byte is handled by converting to []byte first,
// and sending to the dedicated fast-path function for []byte.
//
// Code exists in case our understanding is wrong.
// keep the defensive code behind this flag, so we can remove/hide it if needed.
// For now, we enable the defensive code (ie set it to true).
handleBytesWithinKArray = true
// Support encoding.(Binary|Text)(Unm|M)arshaler.
// This constant flag will enable or disable it.
supportMarshalInterfaces = true
// bytesFreeListNoCache is used for debugging, when we want to skip using a cache of []byte.
bytesFreeListNoCache = false
// size of the cacheline: defaulting to value for archs: amd64, arm64, 386
// should use "runtime/internal/sys".CacheLineSize, but that is not exposed.
cacheLineSize = 64
wordSizeBits = 32 << (^uint(0) >> 63) // strconv.IntSize
wordSize = wordSizeBits / 8
// MARKER: determines whether to skip calling fastpath(En|De)codeTypeSwitch.
// Calling the fastpath switch in encode() or decode() could be redundant,
// as we still have to introspect it again within fnLoad
// to determine the function to use for values of that type.
skipFastpathTypeSwitchInDirectCall = false
)
const cpu32Bit = ^uint(0)>>32 == 0
type rkind byte
const (
rkindPtr = rkind(reflect.Ptr)
rkindString = rkind(reflect.String)
rkindChan = rkind(reflect.Chan)
)
type mapKeyFastKind uint8
const (
mapKeyFastKind32 = iota + 1
mapKeyFastKind32ptr
mapKeyFastKind64
mapKeyFastKind64ptr
mapKeyFastKindStr
)
var (
// use a global mutex to ensure each Handle is initialized.
// We do this, so we don't have to store the basicHandle mutex
// directly in BasicHandle, so it can be shallow-copied.
handleInitMu sync.Mutex
must mustHdl
halt panicHdl
digitCharBitset bitset256
numCharBitset bitset256
whitespaceCharBitset bitset256
asciiAlphaNumBitset bitset256
// numCharWithExpBitset64 bitset64
// numCharNoExpBitset64 bitset64
// whitespaceCharBitset64 bitset64
//
// // hasptrBitset sets bit for all kinds which always have internal pointers
// hasptrBitset bitset32
// refBitset sets bit for all kinds which are direct internal references
refBitset bitset32
// isnilBitset sets bit for all kinds which can be compared to nil
isnilBitset bitset32
// numBoolBitset sets bit for all number and bool kinds
numBoolBitset bitset32
// numBoolStrSliceBitset sets bits for all kinds which are numbers, bool, strings and slices
numBoolStrSliceBitset bitset32
// scalarBitset sets bit for all kinds which are scalars/primitives and thus immutable
scalarBitset bitset32
mapKeyFastKindVals [32]mapKeyFastKind
// codecgen is set to true by codecgen, so that tests, etc can use this information as needed.
codecgen bool
oneByteArr [1]byte
zeroByteSlice = oneByteArr[:0:0]
eofReader devNullReader
)
var (
errMapTypeNotMapKind = errors.New("MapType MUST be of Map Kind")
errSliceTypeNotSliceKind = errors.New("SliceType MUST be of Slice Kind")
errExtFnWriteExtUnsupported = errors.New("BytesExt.WriteExt is not supported")
errExtFnReadExtUnsupported = errors.New("BytesExt.ReadExt is not supported")
errExtFnConvertExtUnsupported = errors.New("InterfaceExt.ConvertExt is not supported")
errExtFnUpdateExtUnsupported = errors.New("InterfaceExt.UpdateExt is not supported")
errPanicUndefined = errors.New("panic: undefined error")
errHandleInited = errors.New("cannot modify initialized Handle")
errNoFormatHandle = errors.New("no handle (cannot identify format)")
)
var pool4tiload = sync.Pool{
New: func() interface{} {
return &typeInfoLoad{
etypes: make([]uintptr, 0, 4),
sfis: make([]structFieldInfo, 0, 4),
sfiNames: make(map[string]uint16, 4),
}
},
}
func init() {
xx := func(f mapKeyFastKind, k ...reflect.Kind) {
for _, v := range k {
mapKeyFastKindVals[byte(v)&31] = f // 'v % 32' equal to 'v & 31'
}
}
var f mapKeyFastKind
f = mapKeyFastKind64
if wordSizeBits == 32 {
f = mapKeyFastKind32
}
xx(f, reflect.Int, reflect.Uint, reflect.Uintptr)
f = mapKeyFastKind64ptr
if wordSizeBits == 32 {
f = mapKeyFastKind32ptr
}
xx(f, reflect.Ptr)
xx(mapKeyFastKindStr, reflect.String)
xx(mapKeyFastKind32, reflect.Uint32, reflect.Int32, reflect.Float32)
xx(mapKeyFastKind64, reflect.Uint64, reflect.Int64, reflect.Float64)
numBoolBitset.
set(byte(reflect.Bool)).
set(byte(reflect.Int)).
set(byte(reflect.Int8)).
set(byte(reflect.Int16)).
set(byte(reflect.Int32)).
set(byte(reflect.Int64)).
set(byte(reflect.Uint)).
set(byte(reflect.Uint8)).
set(byte(reflect.Uint16)).
set(byte(reflect.Uint32)).
set(byte(reflect.Uint64)).
set(byte(reflect.Uintptr)).
set(byte(reflect.Float32)).
set(byte(reflect.Float64)).
set(byte(reflect.Complex64)).
set(byte(reflect.Complex128))
numBoolStrSliceBitset = numBoolBitset
numBoolStrSliceBitset.
set(byte(reflect.String)).
set(byte(reflect.Slice))
scalarBitset = numBoolBitset
scalarBitset.
set(byte(reflect.String))
// MARKER: reflect.Array is not a scalar, as its contents can be modified.
refBitset.
set(byte(reflect.Map)).
set(byte(reflect.Ptr)).
set(byte(reflect.Func)).
set(byte(reflect.Chan)).
set(byte(reflect.UnsafePointer))
isnilBitset = refBitset
isnilBitset.
set(byte(reflect.Interface)).
set(byte(reflect.Slice))
// hasptrBitset = isnilBitset
//
// hasptrBitset.
// set(byte(reflect.String))
for i := byte(0); i <= utf8.RuneSelf; i++ {
if (i >= '0' && i <= '9') || (i >= 'a' && i <= 'z') || (i >= 'A' && i <= 'Z') {
asciiAlphaNumBitset.set(i)
}
switch i {
case ' ', '\t', '\r', '\n':
whitespaceCharBitset.set(i)
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
digitCharBitset.set(i)
numCharBitset.set(i)
case '.', '+', '-':
numCharBitset.set(i)
case 'e', 'E':
numCharBitset.set(i)
}
}
}
// driverStateManager supports the runtime state of an (enc|dec)Driver.
//
// During a side(En|De)code call, we can capture the state, reset it,
// and then restore it later to continue the primary encoding/decoding.
type driverStateManager interface {
resetState()
captureState() interface{}
restoreState(state interface{})
}
type bdAndBdread struct {
bdRead bool
bd byte
}
func (x bdAndBdread) captureState() interface{} { return x }
func (x *bdAndBdread) resetState() { x.bd, x.bdRead = 0, false }
func (x *bdAndBdread) reset() { x.resetState() }
func (x *bdAndBdread) restoreState(v interface{}) { *x = v.(bdAndBdread) }
type clsErr struct {
err error // error on closing
closed bool // is it closed?
}
type charEncoding uint8
const (
_ charEncoding = iota // make 0 unset
cUTF8
cUTF16LE
cUTF16BE
cUTF32LE
cUTF32BE
// Deprecated: not a true char encoding value
cRAW charEncoding = 255
)
// valueType is the stream type
type valueType uint8
const (
valueTypeUnset valueType = iota
valueTypeNil
valueTypeInt
valueTypeUint
valueTypeFloat
valueTypeBool
valueTypeString
valueTypeSymbol
valueTypeBytes
valueTypeMap
valueTypeArray
valueTypeTime
valueTypeExt
// valueTypeInvalid = 0xff
)
var valueTypeStrings = [...]string{
"Unset",
"Nil",
"Int",
"Uint",
"Float",
"Bool",
"String",
"Symbol",
"Bytes",
"Map",
"Array",
"Timestamp",
"Ext",
}
func (x valueType) String() string {
if int(x) < len(valueTypeStrings) {
return valueTypeStrings[x]
}
return strconv.FormatInt(int64(x), 10)
}
// note that containerMapStart and containerArraySend are not sent.
// This is because the ReadXXXStart and EncodeXXXStart already does these.
type containerState uint8
const (
_ containerState = iota
containerMapStart
containerMapKey
containerMapValue
containerMapEnd
containerArrayStart
containerArrayElem
containerArrayEnd
)
// do not recurse if a containing type refers to an embedded type
// which refers back to its containing type (via a pointer).
// The second time this back-reference happens, break out,
// so as not to cause an infinite loop.
const rgetMaxRecursion = 2
// fauxUnion is used to keep track of the primitives decoded.
//
// Without it, we would have to decode each primitive and wrap it
// in an interface{}, causing an allocation.
// In this model, the primitives are decoded in a "pseudo-atomic" fashion,
// so we can rest assured that no other decoding happens while these
// primitives are being decoded.
//
// maps and arrays are not handled by this mechanism.
type fauxUnion struct {
// r RawExt // used for RawExt, uint, []byte.
// primitives below
u uint64
i int64
f float64
l []byte
s string
// ---- cpu cache line boundary?
t time.Time
b bool
// state
v valueType
}
// typeInfoLoad is a transient object used while loading up a typeInfo.
type typeInfoLoad struct {
etypes []uintptr
sfis []structFieldInfo
sfiNames map[string]uint16
}
func (x *typeInfoLoad) reset() {
x.etypes = x.etypes[:0]
x.sfis = x.sfis[:0]
for k := range x.sfiNames { // optimized to zero the map
delete(x.sfiNames, k)
}
}
// mirror json.Marshaler and json.Unmarshaler here,
// so we don't import the encoding/json package
type jsonMarshaler interface {
MarshalJSON() ([]byte, error)
}
type jsonUnmarshaler interface {
UnmarshalJSON([]byte) error
}
type isZeroer interface {
IsZero() bool
}
type isCodecEmptyer interface {
IsCodecEmpty() bool
}
type codecError struct {
err error
name string
pos int
encode bool
}
func (e *codecError) Cause() error {
return e.err
}
func (e *codecError) Unwrap() error {
return e.err
}
func (e *codecError) Error() string {
if e.encode {
return fmt.Sprintf("%s encode error: %v", e.name, e.err)
}
return fmt.Sprintf("%s decode error [pos %d]: %v", e.name, e.pos, e.err)
}
func wrapCodecErr(in error, name string, numbytesread int, encode bool) (out error) {
x, ok := in.(*codecError)
if ok && x.pos == numbytesread && x.name == name && x.encode == encode {
return in
}
return &codecError{in, name, numbytesread, encode}
}
var (
bigen bigenHelper
bigenstd = binary.BigEndian
structInfoFieldName = "_struct"
mapStrIntfTyp = reflect.TypeOf(map[string]interface{}(nil))
mapIntfIntfTyp = reflect.TypeOf(map[interface{}]interface{}(nil))
intfSliceTyp = reflect.TypeOf([]interface{}(nil))
intfTyp = intfSliceTyp.Elem()
reflectValTyp = reflect.TypeOf((*reflect.Value)(nil)).Elem()
stringTyp = reflect.TypeOf("")
timeTyp = reflect.TypeOf(time.Time{})
rawExtTyp = reflect.TypeOf(RawExt{})
rawTyp = reflect.TypeOf(Raw{})
uintptrTyp = reflect.TypeOf(uintptr(0))
uint8Typ = reflect.TypeOf(uint8(0))
uint8SliceTyp = reflect.TypeOf([]uint8(nil))
uintTyp = reflect.TypeOf(uint(0))
intTyp = reflect.TypeOf(int(0))
mapBySliceTyp = reflect.TypeOf((*MapBySlice)(nil)).Elem()
binaryMarshalerTyp = reflect.TypeOf((*encoding.BinaryMarshaler)(nil)).Elem()
binaryUnmarshalerTyp = reflect.TypeOf((*encoding.BinaryUnmarshaler)(nil)).Elem()
textMarshalerTyp = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
textUnmarshalerTyp = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
jsonMarshalerTyp = reflect.TypeOf((*jsonMarshaler)(nil)).Elem()
jsonUnmarshalerTyp = reflect.TypeOf((*jsonUnmarshaler)(nil)).Elem()
selferTyp = reflect.TypeOf((*Selfer)(nil)).Elem()
missingFielderTyp = reflect.TypeOf((*MissingFielder)(nil)).Elem()
iszeroTyp = reflect.TypeOf((*isZeroer)(nil)).Elem()
isCodecEmptyerTyp = reflect.TypeOf((*isCodecEmptyer)(nil)).Elem()
isSelferViaCodecgenerTyp = reflect.TypeOf((*isSelferViaCodecgener)(nil)).Elem()
uint8TypId = rt2id(uint8Typ)
uint8SliceTypId = rt2id(uint8SliceTyp)
rawExtTypId = rt2id(rawExtTyp)
rawTypId = rt2id(rawTyp)
intfTypId = rt2id(intfTyp)
timeTypId = rt2id(timeTyp)
stringTypId = rt2id(stringTyp)
mapStrIntfTypId = rt2id(mapStrIntfTyp)
mapIntfIntfTypId = rt2id(mapIntfIntfTyp)
intfSliceTypId = rt2id(intfSliceTyp)
// mapBySliceTypId = rt2id(mapBySliceTyp)
intBitsize = uint8(intTyp.Bits())
uintBitsize = uint8(uintTyp.Bits())
// bsAll0x00 = []byte{0, 0, 0, 0, 0, 0, 0, 0}
bsAll0xff = []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}
chkOvf checkOverflow
)
var defTypeInfos = NewTypeInfos([]string{"codec", "json"})
// SelfExt is a sentinel extension signifying that types
// registered with it SHOULD be encoded and decoded
// based on the native mode of the format.
//
// This allows users to define a tag for an extension,
// but signify that the types should be encoded/decoded as the native encoding.
// This way, users need not also define how to encode or decode the extension.
var SelfExt = &extFailWrapper{}
// Selfer defines methods by which a value can encode or decode itself.
//
// Any type which implements Selfer will be able to encode or decode itself.
// Consequently, during (en|de)code, this takes precedence over
// (text|binary)(M|Unm)arshal or extension support.
//
// By definition, it is not allowed for a Selfer to directly call Encode or Decode on itself.
// If that is done, Encode/Decode will rightfully fail with a Stack Overflow style error.
// For example, the snippet below will cause such an error.
//
// type testSelferRecur struct{}
// func (s *testSelferRecur) CodecEncodeSelf(e *Encoder) { e.MustEncode(s) }
// func (s *testSelferRecur) CodecDecodeSelf(d *Decoder) { d.MustDecode(s) }
//
// Note: *the first set of bytes of any value MUST NOT represent nil in the format*.
// This is because, during each decode, we first check the the next set of bytes
// represent nil, and if so, we just set the value to nil.
type Selfer interface {
CodecEncodeSelf(*Encoder)
CodecDecodeSelf(*Decoder)
}
type isSelferViaCodecgener interface {
codecSelferViaCodecgen()
}
// MissingFielder defines the interface allowing structs to internally decode or encode
// values which do not map to struct fields.
//
// We expect that this interface is bound to a pointer type (so the mutation function works).
//
// A use-case is if a version of a type unexports a field, but you want compatibility between
// both versions during encoding and decoding.
//
// Note that the interface is completely ignored during codecgen.
type MissingFielder interface {
// CodecMissingField is called to set a missing field and value pair.
//
// It returns true if the missing field was set on the struct.
CodecMissingField(field []byte, value interface{}) bool
// CodecMissingFields returns the set of fields which are not struct fields.
//
// Note that the returned map may be mutated by the caller.
CodecMissingFields() map[string]interface{}
}
// MapBySlice is a tag interface that denotes the slice or array value should encode as a map
// in the stream, and can be decoded from a map in the stream.
//
// The slice or array must contain a sequence of key-value pairs.
// The length of the slice or array must be even (fully divisible by 2).
//
// This affords storing a map in a specific sequence in the stream.
//
// Example usage:
//
// type T1 []string // or []int or []Point or any other "slice" type
// func (_ T1) MapBySlice{} // T1 now implements MapBySlice, and will be encoded as a map
// type T2 struct { KeyValues T1 }
//
// var kvs = []string{"one", "1", "two", "2", "three", "3"}
// var v2 = T2{ KeyValues: T1(kvs) }
// // v2 will be encoded like the map: {"KeyValues": {"one": "1", "two": "2", "three": "3"} }
//
// The support of MapBySlice affords the following:
// - A slice or array type which implements MapBySlice will be encoded as a map
// - A slice can be decoded from a map in the stream
type MapBySlice interface {
MapBySlice()
}
// basicHandleRuntimeState holds onto all BasicHandle runtime and cached config information.
//
// Storing this outside BasicHandle allows us create shallow copies of a Handle,
// which can be used e.g. when we need to modify config fields temporarily.
// Shallow copies are used within tests, so we can modify some config fields for a test
// temporarily when running tests in parallel, without running the risk that a test executing
// in parallel with other tests does not see a transient modified values not meant for it.
type basicHandleRuntimeState struct {
// these are used during runtime.
// At init time, they should have nothing in them.
rtidFns atomicRtidFnSlice
rtidFnsNoExt atomicRtidFnSlice
// Note: basicHandleRuntimeState is not comparable, due to these slices here (extHandle, intf2impls).
// If *[]T is used instead, this becomes comparable, at the cost of extra indirection.
// Thses slices are used all the time, so keep as slices (not pointers).
extHandle
intf2impls
mu sync.Mutex
jsonHandle bool
binaryHandle bool
// timeBuiltin is initialized from TimeNotBuiltin, and used internally.
// once initialized, it cannot be changed, as the function for encoding/decoding time.Time
// will have been cached and the TimeNotBuiltin value will not be consulted thereafter.
timeBuiltin bool
_ bool // padding
}
// BasicHandle encapsulates the common options and extension functions.
//
// Deprecated: DO NOT USE DIRECTLY. EXPORTED FOR GODOC BENEFIT. WILL BE REMOVED.
type BasicHandle struct {
// BasicHandle is always a part of a different type.
// It doesn't have to fit into it own cache lines.
// TypeInfos is used to get the type info for any type.
//
// If not configured, the default TypeInfos is used, which uses struct tag keys: codec, json
TypeInfos *TypeInfos
*basicHandleRuntimeState
// ---- cache line
DecodeOptions
// ---- cache line
EncodeOptions
RPCOptions
// TimeNotBuiltin configures whether time.Time should be treated as a builtin type.
//
// All Handlers should know how to encode/decode time.Time as part of the core
// format specification, or as a standard extension defined by the format.
//
// However, users can elect to handle time.Time as a custom extension, or via the
// standard library's encoding.Binary(M|Unm)arshaler or Text(M|Unm)arshaler interface.
// To elect this behavior, users can set TimeNotBuiltin=true.
//
// Note: Setting TimeNotBuiltin=true can be used to enable the legacy behavior
// (for Cbor and Msgpack), where time.Time was not a builtin supported type.
//
// Note: DO NOT CHANGE AFTER FIRST USE.
//
// Once a Handle has been initialized (used), do not modify this option. It will be ignored.
TimeNotBuiltin bool
// ExplicitRelease is ignored and has no effect.
//
// Deprecated: Pools are only used for long-lived objects shared across goroutines.
// It is maintained for backward compatibility.
ExplicitRelease bool
// ---- cache line
inited uint32 // holds if inited, and also handle flags (binary encoding, json handler, etc)
}
// initHandle does a one-time initialization of the handle.
// After this is run, do not modify the Handle, as some modifications are ignored
// e.g. extensions, registered interfaces, TimeNotBuiltIn, etc
func initHandle(hh Handle) {
x := hh.getBasicHandle()
// MARKER: We need to simulate once.Do, to ensure no data race within the block.
// Consequently, below would not work.
//
// if atomic.CompareAndSwapUint32(&x.inited, 0, 1) {
// x.be = hh.isBinary()
// x.js = hh.isJson
// x.n = hh.Name()[0]
// }
// simulate once.Do using our own stored flag and mutex as a CompareAndSwap
// is not sufficient, since a race condition can occur within init(Handle) function.
// init is made noinline, so that this function can be inlined by its caller.
if atomic.LoadUint32(&x.inited) == 0 {
x.initHandle(hh)
}
}
func (x *BasicHandle) basicInit() {
x.rtidFns.store(nil)
x.rtidFnsNoExt.store(nil)
x.timeBuiltin = !x.TimeNotBuiltin
}
func (x *BasicHandle) init() {}
func (x *BasicHandle) isInited() bool {
return atomic.LoadUint32(&x.inited) != 0
}
// clearInited: DANGEROUS - only use in testing, etc
func (x *BasicHandle) clearInited() {
atomic.StoreUint32(&x.inited, 0)
}
// TimeBuiltin returns whether time.Time OOTB support is used,
// based on the initial configuration of TimeNotBuiltin
func (x *basicHandleRuntimeState) TimeBuiltin() bool {
return x.timeBuiltin
}
func (x *basicHandleRuntimeState) isJs() bool {
return x.jsonHandle
}
func (x *basicHandleRuntimeState) isBe() bool {
return x.binaryHandle
}
func (x *basicHandleRuntimeState) setExt(rt reflect.Type, tag uint64, ext Ext) (err error) {
rk := rt.Kind()
for rk == reflect.Ptr {
rt = rt.Elem()
rk = rt.Kind()
}
if rt.PkgPath() == "" || rk == reflect.Interface { // || rk == reflect.Ptr {
return fmt.Errorf("codec.Handle.SetExt: Takes named type, not a pointer or interface: %v", rt)
}
rtid := rt2id(rt)
// handle all natively supported type appropriately, so they cannot have an extension.
// However, we do not return an error for these, as we do not document that.
// Instead, we silently treat as a no-op, and return.
switch rtid {
case rawTypId, rawExtTypId:
return
case timeTypId:
if x.timeBuiltin {
return
}
}
for i := range x.extHandle {
v := &x.extHandle[i]
if v.rtid == rtid {
v.tag, v.ext = tag, ext
return
}
}
rtidptr := rt2id(reflect.PtrTo(rt))
x.extHandle = append(x.extHandle, extTypeTagFn{rtid, rtidptr, rt, tag, ext})
return
}
// initHandle should be called only from codec.initHandle global function.
// make it uninlineable, as it is called at most once for each handle.
//
//go:noinline
func (x *BasicHandle) initHandle(hh Handle) {
handleInitMu.Lock()
defer handleInitMu.Unlock() // use defer, as halt may panic below
if x.inited == 0 {
if x.basicHandleRuntimeState == nil {
x.basicHandleRuntimeState = new(basicHandleRuntimeState)
}
x.jsonHandle = hh.isJson()
x.binaryHandle = hh.isBinary()
// ensure MapType and SliceType are of correct type
if x.MapType != nil && x.MapType.Kind() != reflect.Map {
halt.onerror(errMapTypeNotMapKind)
}
if x.SliceType != nil && x.SliceType.Kind() != reflect.Slice {
halt.onerror(errSliceTypeNotSliceKind)
}
x.basicInit()
hh.init()
atomic.StoreUint32(&x.inited, 1)
}
}
func (x *BasicHandle) getBasicHandle() *BasicHandle {
return x
}
func (x *BasicHandle) typeInfos() *TypeInfos {
if x.TypeInfos != nil {
return x.TypeInfos
}
return defTypeInfos
}
func (x *BasicHandle) getTypeInfo(rtid uintptr, rt reflect.Type) (pti *typeInfo) {
return x.typeInfos().get(rtid, rt)
}
func findRtidFn(s []codecRtidFn, rtid uintptr) (i uint, fn *codecFn) {
// binary search. adapted from sort/search.go.
// Note: we use goto (instead of for loop) so this can be inlined.
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | true |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ugorji/go/codec/fast-path.generated.go | vendor/github.com/ugorji/go/codec/fast-path.generated.go | //go:build !notfastpath && !codec.notfastpath
// +build !notfastpath,!codec.notfastpath
// Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
// Code generated from fast-path.go.tmpl - DO NOT EDIT.
package codec
// Fast path functions try to create a fast path encode or decode implementation
// for common maps and slices.
//
// We define the functions and register them in this single file
// so as not to pollute the encode.go and decode.go, and create a dependency in there.
// This file can be omitted without causing a build failure.
//
// The advantage of fast paths is:
// - Many calls bypass reflection altogether
//
// Currently support
// - slice of all builtin types (numeric, bool, string, []byte)
// - maps of builtin types to builtin or interface{} type, EXCEPT FOR
// keys of type uintptr, int8/16/32, uint16/32, float32/64, bool, interface{}
// AND values of type type int8/16/32, uint16/32
// This should provide adequate "typical" implementations.
//
// Note that fast track decode functions must handle values for which an address cannot be obtained.
// For example:
// m2 := map[string]int{}
// p2 := []interface{}{m2}
// // decoding into p2 will bomb if fast track functions do not treat like unaddressable.
//
import (
"reflect"
"sort"
)
const fastpathEnabled = true
type fastpathT struct{}
var fastpathTV fastpathT
type fastpathE struct {
rt reflect.Type
encfn func(*Encoder, *codecFnInfo, reflect.Value)
decfn func(*Decoder, *codecFnInfo, reflect.Value)
}
type fastpathA [56]fastpathE
type fastpathARtid [56]uintptr
var fastpathAv fastpathA
var fastpathAvRtid fastpathARtid
type fastpathAslice struct{}
func (fastpathAslice) Len() int { return 56 }
func (fastpathAslice) Less(i, j int) bool {
return fastpathAvRtid[uint(i)] < fastpathAvRtid[uint(j)]
}
func (fastpathAslice) Swap(i, j int) {
fastpathAvRtid[uint(i)], fastpathAvRtid[uint(j)] = fastpathAvRtid[uint(j)], fastpathAvRtid[uint(i)]
fastpathAv[uint(i)], fastpathAv[uint(j)] = fastpathAv[uint(j)], fastpathAv[uint(i)]
}
func fastpathAvIndex(rtid uintptr) int {
// use binary search to grab the index (adapted from sort/search.go)
// Note: we use goto (instead of for loop) so this can be inlined.
// h, i, j := 0, 0, 56
var h, i uint
var j uint = 56
LOOP:
if i < j {
h = (i + j) >> 1 // avoid overflow when computing h // h = i + (j-i)/2
if fastpathAvRtid[h] < rtid {
i = h + 1
} else {
j = h
}
goto LOOP
}
if i < 56 && fastpathAvRtid[i] == rtid {
return int(i)
}
return -1
}
// due to possible initialization loop error, make fastpath in an init()
func init() {
var i uint = 0
fn := func(v interface{},
fe func(*Encoder, *codecFnInfo, reflect.Value),
fd func(*Decoder, *codecFnInfo, reflect.Value)) {
xrt := reflect.TypeOf(v)
xptr := rt2id(xrt)
fastpathAvRtid[i] = xptr
fastpathAv[i] = fastpathE{xrt, fe, fd}
i++
}
fn([]interface{}(nil), (*Encoder).fastpathEncSliceIntfR, (*Decoder).fastpathDecSliceIntfR)
fn([]string(nil), (*Encoder).fastpathEncSliceStringR, (*Decoder).fastpathDecSliceStringR)
fn([][]byte(nil), (*Encoder).fastpathEncSliceBytesR, (*Decoder).fastpathDecSliceBytesR)
fn([]float32(nil), (*Encoder).fastpathEncSliceFloat32R, (*Decoder).fastpathDecSliceFloat32R)
fn([]float64(nil), (*Encoder).fastpathEncSliceFloat64R, (*Decoder).fastpathDecSliceFloat64R)
fn([]uint8(nil), (*Encoder).fastpathEncSliceUint8R, (*Decoder).fastpathDecSliceUint8R)
fn([]uint64(nil), (*Encoder).fastpathEncSliceUint64R, (*Decoder).fastpathDecSliceUint64R)
fn([]int(nil), (*Encoder).fastpathEncSliceIntR, (*Decoder).fastpathDecSliceIntR)
fn([]int32(nil), (*Encoder).fastpathEncSliceInt32R, (*Decoder).fastpathDecSliceInt32R)
fn([]int64(nil), (*Encoder).fastpathEncSliceInt64R, (*Decoder).fastpathDecSliceInt64R)
fn([]bool(nil), (*Encoder).fastpathEncSliceBoolR, (*Decoder).fastpathDecSliceBoolR)
fn(map[string]interface{}(nil), (*Encoder).fastpathEncMapStringIntfR, (*Decoder).fastpathDecMapStringIntfR)
fn(map[string]string(nil), (*Encoder).fastpathEncMapStringStringR, (*Decoder).fastpathDecMapStringStringR)
fn(map[string][]byte(nil), (*Encoder).fastpathEncMapStringBytesR, (*Decoder).fastpathDecMapStringBytesR)
fn(map[string]uint8(nil), (*Encoder).fastpathEncMapStringUint8R, (*Decoder).fastpathDecMapStringUint8R)
fn(map[string]uint64(nil), (*Encoder).fastpathEncMapStringUint64R, (*Decoder).fastpathDecMapStringUint64R)
fn(map[string]int(nil), (*Encoder).fastpathEncMapStringIntR, (*Decoder).fastpathDecMapStringIntR)
fn(map[string]int32(nil), (*Encoder).fastpathEncMapStringInt32R, (*Decoder).fastpathDecMapStringInt32R)
fn(map[string]float64(nil), (*Encoder).fastpathEncMapStringFloat64R, (*Decoder).fastpathDecMapStringFloat64R)
fn(map[string]bool(nil), (*Encoder).fastpathEncMapStringBoolR, (*Decoder).fastpathDecMapStringBoolR)
fn(map[uint8]interface{}(nil), (*Encoder).fastpathEncMapUint8IntfR, (*Decoder).fastpathDecMapUint8IntfR)
fn(map[uint8]string(nil), (*Encoder).fastpathEncMapUint8StringR, (*Decoder).fastpathDecMapUint8StringR)
fn(map[uint8][]byte(nil), (*Encoder).fastpathEncMapUint8BytesR, (*Decoder).fastpathDecMapUint8BytesR)
fn(map[uint8]uint8(nil), (*Encoder).fastpathEncMapUint8Uint8R, (*Decoder).fastpathDecMapUint8Uint8R)
fn(map[uint8]uint64(nil), (*Encoder).fastpathEncMapUint8Uint64R, (*Decoder).fastpathDecMapUint8Uint64R)
fn(map[uint8]int(nil), (*Encoder).fastpathEncMapUint8IntR, (*Decoder).fastpathDecMapUint8IntR)
fn(map[uint8]int32(nil), (*Encoder).fastpathEncMapUint8Int32R, (*Decoder).fastpathDecMapUint8Int32R)
fn(map[uint8]float64(nil), (*Encoder).fastpathEncMapUint8Float64R, (*Decoder).fastpathDecMapUint8Float64R)
fn(map[uint8]bool(nil), (*Encoder).fastpathEncMapUint8BoolR, (*Decoder).fastpathDecMapUint8BoolR)
fn(map[uint64]interface{}(nil), (*Encoder).fastpathEncMapUint64IntfR, (*Decoder).fastpathDecMapUint64IntfR)
fn(map[uint64]string(nil), (*Encoder).fastpathEncMapUint64StringR, (*Decoder).fastpathDecMapUint64StringR)
fn(map[uint64][]byte(nil), (*Encoder).fastpathEncMapUint64BytesR, (*Decoder).fastpathDecMapUint64BytesR)
fn(map[uint64]uint8(nil), (*Encoder).fastpathEncMapUint64Uint8R, (*Decoder).fastpathDecMapUint64Uint8R)
fn(map[uint64]uint64(nil), (*Encoder).fastpathEncMapUint64Uint64R, (*Decoder).fastpathDecMapUint64Uint64R)
fn(map[uint64]int(nil), (*Encoder).fastpathEncMapUint64IntR, (*Decoder).fastpathDecMapUint64IntR)
fn(map[uint64]int32(nil), (*Encoder).fastpathEncMapUint64Int32R, (*Decoder).fastpathDecMapUint64Int32R)
fn(map[uint64]float64(nil), (*Encoder).fastpathEncMapUint64Float64R, (*Decoder).fastpathDecMapUint64Float64R)
fn(map[uint64]bool(nil), (*Encoder).fastpathEncMapUint64BoolR, (*Decoder).fastpathDecMapUint64BoolR)
fn(map[int]interface{}(nil), (*Encoder).fastpathEncMapIntIntfR, (*Decoder).fastpathDecMapIntIntfR)
fn(map[int]string(nil), (*Encoder).fastpathEncMapIntStringR, (*Decoder).fastpathDecMapIntStringR)
fn(map[int][]byte(nil), (*Encoder).fastpathEncMapIntBytesR, (*Decoder).fastpathDecMapIntBytesR)
fn(map[int]uint8(nil), (*Encoder).fastpathEncMapIntUint8R, (*Decoder).fastpathDecMapIntUint8R)
fn(map[int]uint64(nil), (*Encoder).fastpathEncMapIntUint64R, (*Decoder).fastpathDecMapIntUint64R)
fn(map[int]int(nil), (*Encoder).fastpathEncMapIntIntR, (*Decoder).fastpathDecMapIntIntR)
fn(map[int]int32(nil), (*Encoder).fastpathEncMapIntInt32R, (*Decoder).fastpathDecMapIntInt32R)
fn(map[int]float64(nil), (*Encoder).fastpathEncMapIntFloat64R, (*Decoder).fastpathDecMapIntFloat64R)
fn(map[int]bool(nil), (*Encoder).fastpathEncMapIntBoolR, (*Decoder).fastpathDecMapIntBoolR)
fn(map[int32]interface{}(nil), (*Encoder).fastpathEncMapInt32IntfR, (*Decoder).fastpathDecMapInt32IntfR)
fn(map[int32]string(nil), (*Encoder).fastpathEncMapInt32StringR, (*Decoder).fastpathDecMapInt32StringR)
fn(map[int32][]byte(nil), (*Encoder).fastpathEncMapInt32BytesR, (*Decoder).fastpathDecMapInt32BytesR)
fn(map[int32]uint8(nil), (*Encoder).fastpathEncMapInt32Uint8R, (*Decoder).fastpathDecMapInt32Uint8R)
fn(map[int32]uint64(nil), (*Encoder).fastpathEncMapInt32Uint64R, (*Decoder).fastpathDecMapInt32Uint64R)
fn(map[int32]int(nil), (*Encoder).fastpathEncMapInt32IntR, (*Decoder).fastpathDecMapInt32IntR)
fn(map[int32]int32(nil), (*Encoder).fastpathEncMapInt32Int32R, (*Decoder).fastpathDecMapInt32Int32R)
fn(map[int32]float64(nil), (*Encoder).fastpathEncMapInt32Float64R, (*Decoder).fastpathDecMapInt32Float64R)
fn(map[int32]bool(nil), (*Encoder).fastpathEncMapInt32BoolR, (*Decoder).fastpathDecMapInt32BoolR)
sort.Sort(fastpathAslice{})
}
// -- encode
// -- -- fast path type switch
func fastpathEncodeTypeSwitch(iv interface{}, e *Encoder) bool {
switch v := iv.(type) {
case []interface{}:
fastpathTV.EncSliceIntfV(v, e)
case *[]interface{}:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncSliceIntfV(*v, e)
}
case []string:
fastpathTV.EncSliceStringV(v, e)
case *[]string:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncSliceStringV(*v, e)
}
case [][]byte:
fastpathTV.EncSliceBytesV(v, e)
case *[][]byte:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncSliceBytesV(*v, e)
}
case []float32:
fastpathTV.EncSliceFloat32V(v, e)
case *[]float32:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncSliceFloat32V(*v, e)
}
case []float64:
fastpathTV.EncSliceFloat64V(v, e)
case *[]float64:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncSliceFloat64V(*v, e)
}
case []uint8:
fastpathTV.EncSliceUint8V(v, e)
case *[]uint8:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncSliceUint8V(*v, e)
}
case []uint64:
fastpathTV.EncSliceUint64V(v, e)
case *[]uint64:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncSliceUint64V(*v, e)
}
case []int:
fastpathTV.EncSliceIntV(v, e)
case *[]int:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncSliceIntV(*v, e)
}
case []int32:
fastpathTV.EncSliceInt32V(v, e)
case *[]int32:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncSliceInt32V(*v, e)
}
case []int64:
fastpathTV.EncSliceInt64V(v, e)
case *[]int64:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncSliceInt64V(*v, e)
}
case []bool:
fastpathTV.EncSliceBoolV(v, e)
case *[]bool:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncSliceBoolV(*v, e)
}
case map[string]interface{}:
fastpathTV.EncMapStringIntfV(v, e)
case *map[string]interface{}:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapStringIntfV(*v, e)
}
case map[string]string:
fastpathTV.EncMapStringStringV(v, e)
case *map[string]string:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapStringStringV(*v, e)
}
case map[string][]byte:
fastpathTV.EncMapStringBytesV(v, e)
case *map[string][]byte:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapStringBytesV(*v, e)
}
case map[string]uint8:
fastpathTV.EncMapStringUint8V(v, e)
case *map[string]uint8:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapStringUint8V(*v, e)
}
case map[string]uint64:
fastpathTV.EncMapStringUint64V(v, e)
case *map[string]uint64:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapStringUint64V(*v, e)
}
case map[string]int:
fastpathTV.EncMapStringIntV(v, e)
case *map[string]int:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapStringIntV(*v, e)
}
case map[string]int32:
fastpathTV.EncMapStringInt32V(v, e)
case *map[string]int32:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapStringInt32V(*v, e)
}
case map[string]float64:
fastpathTV.EncMapStringFloat64V(v, e)
case *map[string]float64:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapStringFloat64V(*v, e)
}
case map[string]bool:
fastpathTV.EncMapStringBoolV(v, e)
case *map[string]bool:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapStringBoolV(*v, e)
}
case map[uint8]interface{}:
fastpathTV.EncMapUint8IntfV(v, e)
case *map[uint8]interface{}:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapUint8IntfV(*v, e)
}
case map[uint8]string:
fastpathTV.EncMapUint8StringV(v, e)
case *map[uint8]string:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapUint8StringV(*v, e)
}
case map[uint8][]byte:
fastpathTV.EncMapUint8BytesV(v, e)
case *map[uint8][]byte:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapUint8BytesV(*v, e)
}
case map[uint8]uint8:
fastpathTV.EncMapUint8Uint8V(v, e)
case *map[uint8]uint8:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapUint8Uint8V(*v, e)
}
case map[uint8]uint64:
fastpathTV.EncMapUint8Uint64V(v, e)
case *map[uint8]uint64:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapUint8Uint64V(*v, e)
}
case map[uint8]int:
fastpathTV.EncMapUint8IntV(v, e)
case *map[uint8]int:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapUint8IntV(*v, e)
}
case map[uint8]int32:
fastpathTV.EncMapUint8Int32V(v, e)
case *map[uint8]int32:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapUint8Int32V(*v, e)
}
case map[uint8]float64:
fastpathTV.EncMapUint8Float64V(v, e)
case *map[uint8]float64:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapUint8Float64V(*v, e)
}
case map[uint8]bool:
fastpathTV.EncMapUint8BoolV(v, e)
case *map[uint8]bool:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapUint8BoolV(*v, e)
}
case map[uint64]interface{}:
fastpathTV.EncMapUint64IntfV(v, e)
case *map[uint64]interface{}:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapUint64IntfV(*v, e)
}
case map[uint64]string:
fastpathTV.EncMapUint64StringV(v, e)
case *map[uint64]string:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapUint64StringV(*v, e)
}
case map[uint64][]byte:
fastpathTV.EncMapUint64BytesV(v, e)
case *map[uint64][]byte:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapUint64BytesV(*v, e)
}
case map[uint64]uint8:
fastpathTV.EncMapUint64Uint8V(v, e)
case *map[uint64]uint8:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapUint64Uint8V(*v, e)
}
case map[uint64]uint64:
fastpathTV.EncMapUint64Uint64V(v, e)
case *map[uint64]uint64:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapUint64Uint64V(*v, e)
}
case map[uint64]int:
fastpathTV.EncMapUint64IntV(v, e)
case *map[uint64]int:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapUint64IntV(*v, e)
}
case map[uint64]int32:
fastpathTV.EncMapUint64Int32V(v, e)
case *map[uint64]int32:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapUint64Int32V(*v, e)
}
case map[uint64]float64:
fastpathTV.EncMapUint64Float64V(v, e)
case *map[uint64]float64:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapUint64Float64V(*v, e)
}
case map[uint64]bool:
fastpathTV.EncMapUint64BoolV(v, e)
case *map[uint64]bool:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapUint64BoolV(*v, e)
}
case map[int]interface{}:
fastpathTV.EncMapIntIntfV(v, e)
case *map[int]interface{}:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapIntIntfV(*v, e)
}
case map[int]string:
fastpathTV.EncMapIntStringV(v, e)
case *map[int]string:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapIntStringV(*v, e)
}
case map[int][]byte:
fastpathTV.EncMapIntBytesV(v, e)
case *map[int][]byte:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapIntBytesV(*v, e)
}
case map[int]uint8:
fastpathTV.EncMapIntUint8V(v, e)
case *map[int]uint8:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapIntUint8V(*v, e)
}
case map[int]uint64:
fastpathTV.EncMapIntUint64V(v, e)
case *map[int]uint64:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapIntUint64V(*v, e)
}
case map[int]int:
fastpathTV.EncMapIntIntV(v, e)
case *map[int]int:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapIntIntV(*v, e)
}
case map[int]int32:
fastpathTV.EncMapIntInt32V(v, e)
case *map[int]int32:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapIntInt32V(*v, e)
}
case map[int]float64:
fastpathTV.EncMapIntFloat64V(v, e)
case *map[int]float64:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapIntFloat64V(*v, e)
}
case map[int]bool:
fastpathTV.EncMapIntBoolV(v, e)
case *map[int]bool:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapIntBoolV(*v, e)
}
case map[int32]interface{}:
fastpathTV.EncMapInt32IntfV(v, e)
case *map[int32]interface{}:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapInt32IntfV(*v, e)
}
case map[int32]string:
fastpathTV.EncMapInt32StringV(v, e)
case *map[int32]string:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapInt32StringV(*v, e)
}
case map[int32][]byte:
fastpathTV.EncMapInt32BytesV(v, e)
case *map[int32][]byte:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapInt32BytesV(*v, e)
}
case map[int32]uint8:
fastpathTV.EncMapInt32Uint8V(v, e)
case *map[int32]uint8:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapInt32Uint8V(*v, e)
}
case map[int32]uint64:
fastpathTV.EncMapInt32Uint64V(v, e)
case *map[int32]uint64:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapInt32Uint64V(*v, e)
}
case map[int32]int:
fastpathTV.EncMapInt32IntV(v, e)
case *map[int32]int:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapInt32IntV(*v, e)
}
case map[int32]int32:
fastpathTV.EncMapInt32Int32V(v, e)
case *map[int32]int32:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapInt32Int32V(*v, e)
}
case map[int32]float64:
fastpathTV.EncMapInt32Float64V(v, e)
case *map[int32]float64:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapInt32Float64V(*v, e)
}
case map[int32]bool:
fastpathTV.EncMapInt32BoolV(v, e)
case *map[int32]bool:
if *v == nil {
e.e.EncodeNil()
} else {
fastpathTV.EncMapInt32BoolV(*v, e)
}
default:
_ = v // workaround https://github.com/golang/go/issues/12927 seen in go1.4
return false
}
return true
}
// -- -- fast path functions
func (e *Encoder) fastpathEncSliceIntfR(f *codecFnInfo, rv reflect.Value) {
var v []interface{}
if rv.Kind() == reflect.Array {
rvGetSlice4Array(rv, &v)
} else {
v = rv2i(rv).([]interface{})
}
if f.ti.mbs {
fastpathTV.EncAsMapSliceIntfV(v, e)
} else {
fastpathTV.EncSliceIntfV(v, e)
}
}
func (fastpathT) EncSliceIntfV(v []interface{}, e *Encoder) {
e.arrayStart(len(v))
for j := range v {
e.arrayElem()
e.encode(v[j])
}
e.arrayEnd()
}
func (fastpathT) EncAsMapSliceIntfV(v []interface{}, e *Encoder) {
e.haltOnMbsOddLen(len(v))
e.mapStart(len(v) >> 1) // e.mapStart(len(v) / 2)
for j := range v {
if j&1 == 0 { // if j%2 == 0 {
e.mapElemKey()
} else {
e.mapElemValue()
}
e.encode(v[j])
}
e.mapEnd()
}
func (e *Encoder) fastpathEncSliceStringR(f *codecFnInfo, rv reflect.Value) {
var v []string
if rv.Kind() == reflect.Array {
rvGetSlice4Array(rv, &v)
} else {
v = rv2i(rv).([]string)
}
if f.ti.mbs {
fastpathTV.EncAsMapSliceStringV(v, e)
} else {
fastpathTV.EncSliceStringV(v, e)
}
}
func (fastpathT) EncSliceStringV(v []string, e *Encoder) {
e.arrayStart(len(v))
for j := range v {
e.arrayElem()
e.e.EncodeString(v[j])
}
e.arrayEnd()
}
func (fastpathT) EncAsMapSliceStringV(v []string, e *Encoder) {
e.haltOnMbsOddLen(len(v))
e.mapStart(len(v) >> 1) // e.mapStart(len(v) / 2)
for j := range v {
if j&1 == 0 { // if j%2 == 0 {
e.mapElemKey()
} else {
e.mapElemValue()
}
e.e.EncodeString(v[j])
}
e.mapEnd()
}
func (e *Encoder) fastpathEncSliceBytesR(f *codecFnInfo, rv reflect.Value) {
var v [][]byte
if rv.Kind() == reflect.Array {
rvGetSlice4Array(rv, &v)
} else {
v = rv2i(rv).([][]byte)
}
if f.ti.mbs {
fastpathTV.EncAsMapSliceBytesV(v, e)
} else {
fastpathTV.EncSliceBytesV(v, e)
}
}
func (fastpathT) EncSliceBytesV(v [][]byte, e *Encoder) {
e.arrayStart(len(v))
for j := range v {
e.arrayElem()
e.e.EncodeStringBytesRaw(v[j])
}
e.arrayEnd()
}
func (fastpathT) EncAsMapSliceBytesV(v [][]byte, e *Encoder) {
e.haltOnMbsOddLen(len(v))
e.mapStart(len(v) >> 1) // e.mapStart(len(v) / 2)
for j := range v {
if j&1 == 0 { // if j%2 == 0 {
e.mapElemKey()
} else {
e.mapElemValue()
}
e.e.EncodeStringBytesRaw(v[j])
}
e.mapEnd()
}
func (e *Encoder) fastpathEncSliceFloat32R(f *codecFnInfo, rv reflect.Value) {
var v []float32
if rv.Kind() == reflect.Array {
rvGetSlice4Array(rv, &v)
} else {
v = rv2i(rv).([]float32)
}
if f.ti.mbs {
fastpathTV.EncAsMapSliceFloat32V(v, e)
} else {
fastpathTV.EncSliceFloat32V(v, e)
}
}
func (fastpathT) EncSliceFloat32V(v []float32, e *Encoder) {
e.arrayStart(len(v))
for j := range v {
e.arrayElem()
e.e.EncodeFloat32(v[j])
}
e.arrayEnd()
}
func (fastpathT) EncAsMapSliceFloat32V(v []float32, e *Encoder) {
e.haltOnMbsOddLen(len(v))
e.mapStart(len(v) >> 1) // e.mapStart(len(v) / 2)
for j := range v {
if j&1 == 0 { // if j%2 == 0 {
e.mapElemKey()
} else {
e.mapElemValue()
}
e.e.EncodeFloat32(v[j])
}
e.mapEnd()
}
func (e *Encoder) fastpathEncSliceFloat64R(f *codecFnInfo, rv reflect.Value) {
var v []float64
if rv.Kind() == reflect.Array {
rvGetSlice4Array(rv, &v)
} else {
v = rv2i(rv).([]float64)
}
if f.ti.mbs {
fastpathTV.EncAsMapSliceFloat64V(v, e)
} else {
fastpathTV.EncSliceFloat64V(v, e)
}
}
func (fastpathT) EncSliceFloat64V(v []float64, e *Encoder) {
e.arrayStart(len(v))
for j := range v {
e.arrayElem()
e.e.EncodeFloat64(v[j])
}
e.arrayEnd()
}
func (fastpathT) EncAsMapSliceFloat64V(v []float64, e *Encoder) {
e.haltOnMbsOddLen(len(v))
e.mapStart(len(v) >> 1) // e.mapStart(len(v) / 2)
for j := range v {
if j&1 == 0 { // if j%2 == 0 {
e.mapElemKey()
} else {
e.mapElemValue()
}
e.e.EncodeFloat64(v[j])
}
e.mapEnd()
}
func (e *Encoder) fastpathEncSliceUint8R(f *codecFnInfo, rv reflect.Value) {
var v []uint8
if rv.Kind() == reflect.Array {
rvGetSlice4Array(rv, &v)
} else {
v = rv2i(rv).([]uint8)
}
if f.ti.mbs {
fastpathTV.EncAsMapSliceUint8V(v, e)
} else {
fastpathTV.EncSliceUint8V(v, e)
}
}
func (fastpathT) EncSliceUint8V(v []uint8, e *Encoder) {
e.e.EncodeStringBytesRaw(v)
}
func (fastpathT) EncAsMapSliceUint8V(v []uint8, e *Encoder) {
e.haltOnMbsOddLen(len(v))
e.mapStart(len(v) >> 1) // e.mapStart(len(v) / 2)
for j := range v {
if j&1 == 0 { // if j%2 == 0 {
e.mapElemKey()
} else {
e.mapElemValue()
}
e.e.EncodeUint(uint64(v[j]))
}
e.mapEnd()
}
func (e *Encoder) fastpathEncSliceUint64R(f *codecFnInfo, rv reflect.Value) {
var v []uint64
if rv.Kind() == reflect.Array {
rvGetSlice4Array(rv, &v)
} else {
v = rv2i(rv).([]uint64)
}
if f.ti.mbs {
fastpathTV.EncAsMapSliceUint64V(v, e)
} else {
fastpathTV.EncSliceUint64V(v, e)
}
}
func (fastpathT) EncSliceUint64V(v []uint64, e *Encoder) {
e.arrayStart(len(v))
for j := range v {
e.arrayElem()
e.e.EncodeUint(v[j])
}
e.arrayEnd()
}
func (fastpathT) EncAsMapSliceUint64V(v []uint64, e *Encoder) {
e.haltOnMbsOddLen(len(v))
e.mapStart(len(v) >> 1) // e.mapStart(len(v) / 2)
for j := range v {
if j&1 == 0 { // if j%2 == 0 {
e.mapElemKey()
} else {
e.mapElemValue()
}
e.e.EncodeUint(v[j])
}
e.mapEnd()
}
func (e *Encoder) fastpathEncSliceIntR(f *codecFnInfo, rv reflect.Value) {
var v []int
if rv.Kind() == reflect.Array {
rvGetSlice4Array(rv, &v)
} else {
v = rv2i(rv).([]int)
}
if f.ti.mbs {
fastpathTV.EncAsMapSliceIntV(v, e)
} else {
fastpathTV.EncSliceIntV(v, e)
}
}
func (fastpathT) EncSliceIntV(v []int, e *Encoder) {
e.arrayStart(len(v))
for j := range v {
e.arrayElem()
e.e.EncodeInt(int64(v[j]))
}
e.arrayEnd()
}
func (fastpathT) EncAsMapSliceIntV(v []int, e *Encoder) {
e.haltOnMbsOddLen(len(v))
e.mapStart(len(v) >> 1) // e.mapStart(len(v) / 2)
for j := range v {
if j&1 == 0 { // if j%2 == 0 {
e.mapElemKey()
} else {
e.mapElemValue()
}
e.e.EncodeInt(int64(v[j]))
}
e.mapEnd()
}
func (e *Encoder) fastpathEncSliceInt32R(f *codecFnInfo, rv reflect.Value) {
var v []int32
if rv.Kind() == reflect.Array {
rvGetSlice4Array(rv, &v)
} else {
v = rv2i(rv).([]int32)
}
if f.ti.mbs {
fastpathTV.EncAsMapSliceInt32V(v, e)
} else {
fastpathTV.EncSliceInt32V(v, e)
}
}
func (fastpathT) EncSliceInt32V(v []int32, e *Encoder) {
e.arrayStart(len(v))
for j := range v {
e.arrayElem()
e.e.EncodeInt(int64(v[j]))
}
e.arrayEnd()
}
func (fastpathT) EncAsMapSliceInt32V(v []int32, e *Encoder) {
e.haltOnMbsOddLen(len(v))
e.mapStart(len(v) >> 1) // e.mapStart(len(v) / 2)
for j := range v {
if j&1 == 0 { // if j%2 == 0 {
e.mapElemKey()
} else {
e.mapElemValue()
}
e.e.EncodeInt(int64(v[j]))
}
e.mapEnd()
}
func (e *Encoder) fastpathEncSliceInt64R(f *codecFnInfo, rv reflect.Value) {
var v []int64
if rv.Kind() == reflect.Array {
rvGetSlice4Array(rv, &v)
} else {
v = rv2i(rv).([]int64)
}
if f.ti.mbs {
fastpathTV.EncAsMapSliceInt64V(v, e)
} else {
fastpathTV.EncSliceInt64V(v, e)
}
}
func (fastpathT) EncSliceInt64V(v []int64, e *Encoder) {
e.arrayStart(len(v))
for j := range v {
e.arrayElem()
e.e.EncodeInt(v[j])
}
e.arrayEnd()
}
func (fastpathT) EncAsMapSliceInt64V(v []int64, e *Encoder) {
e.haltOnMbsOddLen(len(v))
e.mapStart(len(v) >> 1) // e.mapStart(len(v) / 2)
for j := range v {
if j&1 == 0 { // if j%2 == 0 {
e.mapElemKey()
} else {
e.mapElemValue()
}
e.e.EncodeInt(v[j])
}
e.mapEnd()
}
func (e *Encoder) fastpathEncSliceBoolR(f *codecFnInfo, rv reflect.Value) {
var v []bool
if rv.Kind() == reflect.Array {
rvGetSlice4Array(rv, &v)
} else {
v = rv2i(rv).([]bool)
}
if f.ti.mbs {
fastpathTV.EncAsMapSliceBoolV(v, e)
} else {
fastpathTV.EncSliceBoolV(v, e)
}
}
func (fastpathT) EncSliceBoolV(v []bool, e *Encoder) {
e.arrayStart(len(v))
for j := range v {
e.arrayElem()
e.e.EncodeBool(v[j])
}
e.arrayEnd()
}
func (fastpathT) EncAsMapSliceBoolV(v []bool, e *Encoder) {
e.haltOnMbsOddLen(len(v))
e.mapStart(len(v) >> 1) // e.mapStart(len(v) / 2)
for j := range v {
if j&1 == 0 { // if j%2 == 0 {
e.mapElemKey()
} else {
e.mapElemValue()
}
e.e.EncodeBool(v[j])
}
e.mapEnd()
}
func (e *Encoder) fastpathEncMapStringIntfR(f *codecFnInfo, rv reflect.Value) {
fastpathTV.EncMapStringIntfV(rv2i(rv).(map[string]interface{}), e)
}
func (fastpathT) EncMapStringIntfV(v map[string]interface{}, e *Encoder) {
e.mapStart(len(v))
if e.h.Canonical {
v2 := make([]string, len(v))
var i uint
for k := range v {
v2[i] = k
i++
}
sort.Sort(stringSlice(v2))
for _, k2 := range v2 {
e.mapElemKey()
e.e.EncodeString(k2)
e.mapElemValue()
e.encode(v[k2])
}
} else {
for k2, v2 := range v {
e.mapElemKey()
e.e.EncodeString(k2)
e.mapElemValue()
e.encode(v2)
}
}
e.mapEnd()
}
func (e *Encoder) fastpathEncMapStringStringR(f *codecFnInfo, rv reflect.Value) {
fastpathTV.EncMapStringStringV(rv2i(rv).(map[string]string), e)
}
func (fastpathT) EncMapStringStringV(v map[string]string, e *Encoder) {
e.mapStart(len(v))
if e.h.Canonical {
v2 := make([]string, len(v))
var i uint
for k := range v {
v2[i] = k
i++
}
sort.Sort(stringSlice(v2))
for _, k2 := range v2 {
e.mapElemKey()
e.e.EncodeString(k2)
e.mapElemValue()
e.e.EncodeString(v[k2])
}
} else {
for k2, v2 := range v {
e.mapElemKey()
e.e.EncodeString(k2)
e.mapElemValue()
e.e.EncodeString(v2)
}
}
e.mapEnd()
}
func (e *Encoder) fastpathEncMapStringBytesR(f *codecFnInfo, rv reflect.Value) {
fastpathTV.EncMapStringBytesV(rv2i(rv).(map[string][]byte), e)
}
func (fastpathT) EncMapStringBytesV(v map[string][]byte, e *Encoder) {
e.mapStart(len(v))
if e.h.Canonical {
v2 := make([]string, len(v))
var i uint
for k := range v {
v2[i] = k
i++
}
sort.Sort(stringSlice(v2))
for _, k2 := range v2 {
e.mapElemKey()
e.e.EncodeString(k2)
e.mapElemValue()
e.e.EncodeStringBytesRaw(v[k2])
}
} else {
for k2, v2 := range v {
e.mapElemKey()
e.e.EncodeString(k2)
e.mapElemValue()
e.e.EncodeStringBytesRaw(v2)
}
}
e.mapEnd()
}
func (e *Encoder) fastpathEncMapStringUint8R(f *codecFnInfo, rv reflect.Value) {
fastpathTV.EncMapStringUint8V(rv2i(rv).(map[string]uint8), e)
}
func (fastpathT) EncMapStringUint8V(v map[string]uint8, e *Encoder) {
e.mapStart(len(v))
if e.h.Canonical {
v2 := make([]string, len(v))
var i uint
for k := range v {
v2[i] = k
i++
}
sort.Sort(stringSlice(v2))
for _, k2 := range v2 {
e.mapElemKey()
e.e.EncodeString(k2)
e.mapElemValue()
e.e.EncodeUint(uint64(v[k2]))
}
} else {
for k2, v2 := range v {
e.mapElemKey()
e.e.EncodeString(k2)
e.mapElemValue()
e.e.EncodeUint(uint64(v2))
}
}
e.mapEnd()
}
func (e *Encoder) fastpathEncMapStringUint64R(f *codecFnInfo, rv reflect.Value) {
fastpathTV.EncMapStringUint64V(rv2i(rv).(map[string]uint64), e)
}
func (fastpathT) EncMapStringUint64V(v map[string]uint64, e *Encoder) {
e.mapStart(len(v))
if e.h.Canonical {
v2 := make([]string, len(v))
var i uint
for k := range v {
v2[i] = k
i++
}
sort.Sort(stringSlice(v2))
for _, k2 := range v2 {
e.mapElemKey()
e.e.EncodeString(k2)
e.mapElemValue()
e.e.EncodeUint(v[k2])
}
} else {
for k2, v2 := range v {
e.mapElemKey()
e.e.EncodeString(k2)
e.mapElemValue()
e.e.EncodeUint(v2)
}
}
e.mapEnd()
}
func (e *Encoder) fastpathEncMapStringIntR(f *codecFnInfo, rv reflect.Value) {
fastpathTV.EncMapStringIntV(rv2i(rv).(map[string]int), e)
}
func (fastpathT) EncMapStringIntV(v map[string]int, e *Encoder) {
e.mapStart(len(v))
if e.h.Canonical {
v2 := make([]string, len(v))
var i uint
for k := range v {
v2[i] = k
i++
}
sort.Sort(stringSlice(v2))
for _, k2 := range v2 {
e.mapElemKey()
e.e.EncodeString(k2)
e.mapElemValue()
e.e.EncodeInt(int64(v[k2]))
}
} else {
for k2, v2 := range v {
e.mapElemKey()
e.e.EncodeString(k2)
e.mapElemValue()
e.e.EncodeInt(int64(v2))
}
}
e.mapEnd()
}
func (e *Encoder) fastpathEncMapStringInt32R(f *codecFnInfo, rv reflect.Value) {
fastpathTV.EncMapStringInt32V(rv2i(rv).(map[string]int32), e)
}
func (fastpathT) EncMapStringInt32V(v map[string]int32, e *Encoder) {
e.mapStart(len(v))
if e.h.Canonical {
v2 := make([]string, len(v))
var i uint
for k := range v {
v2[i] = k
i++
}
sort.Sort(stringSlice(v2))
for _, k2 := range v2 {
e.mapElemKey()
e.e.EncodeString(k2)
e.mapElemValue()
e.e.EncodeInt(int64(v[k2]))
}
} else {
for k2, v2 := range v {
e.mapElemKey()
e.e.EncodeString(k2)
e.mapElemValue()
e.e.EncodeInt(int64(v2))
}
}
e.mapEnd()
}
func (e *Encoder) fastpathEncMapStringFloat64R(f *codecFnInfo, rv reflect.Value) {
fastpathTV.EncMapStringFloat64V(rv2i(rv).(map[string]float64), e)
}
func (fastpathT) EncMapStringFloat64V(v map[string]float64, e *Encoder) {
e.mapStart(len(v))
if e.h.Canonical {
v2 := make([]string, len(v))
var i uint
for k := range v {
v2[i] = k
i++
}
sort.Sort(stringSlice(v2))
for _, k2 := range v2 {
e.mapElemKey()
e.e.EncodeString(k2)
e.mapElemValue()
e.e.EncodeFloat64(v[k2])
}
} else {
for k2, v2 := range v {
e.mapElemKey()
e.e.EncodeString(k2)
e.mapElemValue()
e.e.EncodeFloat64(v2)
}
}
e.mapEnd()
}
func (e *Encoder) fastpathEncMapStringBoolR(f *codecFnInfo, rv reflect.Value) {
fastpathTV.EncMapStringBoolV(rv2i(rv).(map[string]bool), e)
}
func (fastpathT) EncMapStringBoolV(v map[string]bool, e *Encoder) {
e.mapStart(len(v))
if e.h.Canonical {
v2 := make([]string, len(v))
var i uint
for k := range v {
v2[i] = k
i++
}
sort.Sort(stringSlice(v2))
for _, k2 := range v2 {
e.mapElemKey()
e.e.EncodeString(k2)
e.mapElemValue()
e.e.EncodeBool(v[k2])
}
} else {
for k2, v2 := range v {
e.mapElemKey()
e.e.EncodeString(k2)
e.mapElemValue()
e.e.EncodeBool(v2)
}
}
e.mapEnd()
}
func (e *Encoder) fastpathEncMapUint8IntfR(f *codecFnInfo, rv reflect.Value) {
fastpathTV.EncMapUint8IntfV(rv2i(rv).(map[uint8]interface{}), e)
}
func (fastpathT) EncMapUint8IntfV(v map[uint8]interface{}, e *Encoder) {
e.mapStart(len(v))
if e.h.Canonical {
v2 := make([]uint8, len(v))
var i uint
for k := range v {
v2[i] = k
i++
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | true |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ugorji/go/codec/msgpack.go | vendor/github.com/ugorji/go/codec/msgpack.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
/*
Msgpack-c implementation powers the c, c++, python, ruby, etc libraries.
We need to maintain compatibility with it and how it encodes integer values
without caring about the type.
For compatibility with behaviour of msgpack-c reference implementation:
- Go intX (>0) and uintX
IS ENCODED AS
msgpack +ve fixnum, unsigned
- Go intX (<0)
IS ENCODED AS
msgpack -ve fixnum, signed
*/
package codec
import (
"fmt"
"io"
"math"
"net/rpc"
"reflect"
"time"
"unicode/utf8"
)
const (
mpPosFixNumMin byte = 0x00
mpPosFixNumMax byte = 0x7f
mpFixMapMin byte = 0x80
mpFixMapMax byte = 0x8f
mpFixArrayMin byte = 0x90
mpFixArrayMax byte = 0x9f
mpFixStrMin byte = 0xa0
mpFixStrMax byte = 0xbf
mpNil byte = 0xc0
_ byte = 0xc1
mpFalse byte = 0xc2
mpTrue byte = 0xc3
mpFloat byte = 0xca
mpDouble byte = 0xcb
mpUint8 byte = 0xcc
mpUint16 byte = 0xcd
mpUint32 byte = 0xce
mpUint64 byte = 0xcf
mpInt8 byte = 0xd0
mpInt16 byte = 0xd1
mpInt32 byte = 0xd2
mpInt64 byte = 0xd3
// extensions below
mpBin8 byte = 0xc4
mpBin16 byte = 0xc5
mpBin32 byte = 0xc6
mpExt8 byte = 0xc7
mpExt16 byte = 0xc8
mpExt32 byte = 0xc9
mpFixExt1 byte = 0xd4
mpFixExt2 byte = 0xd5
mpFixExt4 byte = 0xd6
mpFixExt8 byte = 0xd7
mpFixExt16 byte = 0xd8
mpStr8 byte = 0xd9 // new
mpStr16 byte = 0xda
mpStr32 byte = 0xdb
mpArray16 byte = 0xdc
mpArray32 byte = 0xdd
mpMap16 byte = 0xde
mpMap32 byte = 0xdf
mpNegFixNumMin byte = 0xe0
mpNegFixNumMax byte = 0xff
)
var mpTimeExtTag int8 = -1
var mpTimeExtTagU = uint8(mpTimeExtTag)
var mpdescNames = map[byte]string{
mpNil: "nil",
mpFalse: "false",
mpTrue: "true",
mpFloat: "float",
mpDouble: "float",
mpUint8: "uuint",
mpUint16: "uint",
mpUint32: "uint",
mpUint64: "uint",
mpInt8: "int",
mpInt16: "int",
mpInt32: "int",
mpInt64: "int",
mpStr8: "string|bytes",
mpStr16: "string|bytes",
mpStr32: "string|bytes",
mpBin8: "bytes",
mpBin16: "bytes",
mpBin32: "bytes",
mpArray16: "array",
mpArray32: "array",
mpMap16: "map",
mpMap32: "map",
}
func mpdesc(bd byte) (s string) {
s = mpdescNames[bd]
if s == "" {
switch {
case bd >= mpPosFixNumMin && bd <= mpPosFixNumMax,
bd >= mpNegFixNumMin && bd <= mpNegFixNumMax:
s = "int"
case bd >= mpFixStrMin && bd <= mpFixStrMax:
s = "string|bytes"
case bd >= mpFixArrayMin && bd <= mpFixArrayMax:
s = "array"
case bd >= mpFixMapMin && bd <= mpFixMapMax:
s = "map"
case bd >= mpFixExt1 && bd <= mpFixExt16,
bd >= mpExt8 && bd <= mpExt32:
s = "ext"
default:
s = "unknown"
}
}
return
}
// MsgpackSpecRpcMultiArgs is a special type which signifies to the MsgpackSpecRpcCodec
// that the backend RPC service takes multiple arguments, which have been arranged
// in sequence in the slice.
//
// The Codec then passes it AS-IS to the rpc service (without wrapping it in an
// array of 1 element).
type MsgpackSpecRpcMultiArgs []interface{}
// A MsgpackContainer type specifies the different types of msgpackContainers.
type msgpackContainerType struct {
fixCutoff, bFixMin, b8, b16, b32 byte
// hasFixMin, has8, has8Always bool
}
var (
msgpackContainerRawLegacy = msgpackContainerType{
32, mpFixStrMin, 0, mpStr16, mpStr32,
}
msgpackContainerStr = msgpackContainerType{
32, mpFixStrMin, mpStr8, mpStr16, mpStr32, // true, true, false,
}
msgpackContainerBin = msgpackContainerType{
0, 0, mpBin8, mpBin16, mpBin32, // false, true, true,
}
msgpackContainerList = msgpackContainerType{
16, mpFixArrayMin, 0, mpArray16, mpArray32, // true, false, false,
}
msgpackContainerMap = msgpackContainerType{
16, mpFixMapMin, 0, mpMap16, mpMap32, // true, false, false,
}
)
//---------------------------------------------
type msgpackEncDriver struct {
noBuiltInTypes
encDriverNoopContainerWriter
encDriverNoState
h *MsgpackHandle
// x [8]byte
e Encoder
}
func (e *msgpackEncDriver) encoder() *Encoder {
return &e.e
}
func (e *msgpackEncDriver) EncodeNil() {
e.e.encWr.writen1(mpNil)
}
func (e *msgpackEncDriver) EncodeInt(i int64) {
if e.h.PositiveIntUnsigned && i >= 0 {
e.EncodeUint(uint64(i))
} else if i > math.MaxInt8 {
if i <= math.MaxInt16 {
e.e.encWr.writen1(mpInt16)
bigen.writeUint16(e.e.w(), uint16(i))
} else if i <= math.MaxInt32 {
e.e.encWr.writen1(mpInt32)
bigen.writeUint32(e.e.w(), uint32(i))
} else {
e.e.encWr.writen1(mpInt64)
bigen.writeUint64(e.e.w(), uint64(i))
}
} else if i >= -32 {
if e.h.NoFixedNum {
e.e.encWr.writen2(mpInt8, byte(i))
} else {
e.e.encWr.writen1(byte(i))
}
} else if i >= math.MinInt8 {
e.e.encWr.writen2(mpInt8, byte(i))
} else if i >= math.MinInt16 {
e.e.encWr.writen1(mpInt16)
bigen.writeUint16(e.e.w(), uint16(i))
} else if i >= math.MinInt32 {
e.e.encWr.writen1(mpInt32)
bigen.writeUint32(e.e.w(), uint32(i))
} else {
e.e.encWr.writen1(mpInt64)
bigen.writeUint64(e.e.w(), uint64(i))
}
}
func (e *msgpackEncDriver) EncodeUint(i uint64) {
if i <= math.MaxInt8 {
if e.h.NoFixedNum {
e.e.encWr.writen2(mpUint8, byte(i))
} else {
e.e.encWr.writen1(byte(i))
}
} else if i <= math.MaxUint8 {
e.e.encWr.writen2(mpUint8, byte(i))
} else if i <= math.MaxUint16 {
e.e.encWr.writen1(mpUint16)
bigen.writeUint16(e.e.w(), uint16(i))
} else if i <= math.MaxUint32 {
e.e.encWr.writen1(mpUint32)
bigen.writeUint32(e.e.w(), uint32(i))
} else {
e.e.encWr.writen1(mpUint64)
bigen.writeUint64(e.e.w(), uint64(i))
}
}
func (e *msgpackEncDriver) EncodeBool(b bool) {
if b {
e.e.encWr.writen1(mpTrue)
} else {
e.e.encWr.writen1(mpFalse)
}
}
func (e *msgpackEncDriver) EncodeFloat32(f float32) {
e.e.encWr.writen1(mpFloat)
bigen.writeUint32(e.e.w(), math.Float32bits(f))
}
func (e *msgpackEncDriver) EncodeFloat64(f float64) {
e.e.encWr.writen1(mpDouble)
bigen.writeUint64(e.e.w(), math.Float64bits(f))
}
func (e *msgpackEncDriver) EncodeTime(t time.Time) {
if t.IsZero() {
e.EncodeNil()
return
}
t = t.UTC()
sec, nsec := t.Unix(), uint64(t.Nanosecond())
var data64 uint64
var l = 4
if sec >= 0 && sec>>34 == 0 {
data64 = (nsec << 34) | uint64(sec)
if data64&0xffffffff00000000 != 0 {
l = 8
}
} else {
l = 12
}
if e.h.WriteExt {
e.encodeExtPreamble(mpTimeExtTagU, l)
} else {
e.writeContainerLen(msgpackContainerRawLegacy, l)
}
switch l {
case 4:
bigen.writeUint32(e.e.w(), uint32(data64))
case 8:
bigen.writeUint64(e.e.w(), data64)
case 12:
bigen.writeUint32(e.e.w(), uint32(nsec))
bigen.writeUint64(e.e.w(), uint64(sec))
}
}
func (e *msgpackEncDriver) EncodeExt(v interface{}, basetype reflect.Type, xtag uint64, ext Ext) {
var bs0, bs []byte
if ext == SelfExt {
bs0 = e.e.blist.get(1024)
bs = bs0
e.e.sideEncode(v, basetype, &bs)
} else {
bs = ext.WriteExt(v)
}
if bs == nil {
e.EncodeNil()
goto END
}
if e.h.WriteExt {
e.encodeExtPreamble(uint8(xtag), len(bs))
e.e.encWr.writeb(bs)
} else {
e.EncodeStringBytesRaw(bs)
}
END:
if ext == SelfExt {
e.e.blist.put(bs)
if !byteSliceSameData(bs0, bs) {
e.e.blist.put(bs0)
}
}
}
func (e *msgpackEncDriver) EncodeRawExt(re *RawExt) {
e.encodeExtPreamble(uint8(re.Tag), len(re.Data))
e.e.encWr.writeb(re.Data)
}
func (e *msgpackEncDriver) encodeExtPreamble(xtag byte, l int) {
if l == 1 {
e.e.encWr.writen2(mpFixExt1, xtag)
} else if l == 2 {
e.e.encWr.writen2(mpFixExt2, xtag)
} else if l == 4 {
e.e.encWr.writen2(mpFixExt4, xtag)
} else if l == 8 {
e.e.encWr.writen2(mpFixExt8, xtag)
} else if l == 16 {
e.e.encWr.writen2(mpFixExt16, xtag)
} else if l < 256 {
e.e.encWr.writen2(mpExt8, byte(l))
e.e.encWr.writen1(xtag)
} else if l < 65536 {
e.e.encWr.writen1(mpExt16)
bigen.writeUint16(e.e.w(), uint16(l))
e.e.encWr.writen1(xtag)
} else {
e.e.encWr.writen1(mpExt32)
bigen.writeUint32(e.e.w(), uint32(l))
e.e.encWr.writen1(xtag)
}
}
func (e *msgpackEncDriver) WriteArrayStart(length int) {
e.writeContainerLen(msgpackContainerList, length)
}
func (e *msgpackEncDriver) WriteMapStart(length int) {
e.writeContainerLen(msgpackContainerMap, length)
}
func (e *msgpackEncDriver) EncodeString(s string) {
var ct msgpackContainerType
if e.h.WriteExt {
if e.h.StringToRaw {
ct = msgpackContainerBin
} else {
ct = msgpackContainerStr
}
} else {
ct = msgpackContainerRawLegacy
}
e.writeContainerLen(ct, len(s))
if len(s) > 0 {
e.e.encWr.writestr(s)
}
}
func (e *msgpackEncDriver) EncodeStringBytesRaw(bs []byte) {
if bs == nil {
e.EncodeNil()
return
}
if e.h.WriteExt {
e.writeContainerLen(msgpackContainerBin, len(bs))
} else {
e.writeContainerLen(msgpackContainerRawLegacy, len(bs))
}
if len(bs) > 0 {
e.e.encWr.writeb(bs)
}
}
func (e *msgpackEncDriver) writeContainerLen(ct msgpackContainerType, l int) {
if ct.fixCutoff > 0 && l < int(ct.fixCutoff) {
e.e.encWr.writen1(ct.bFixMin | byte(l))
} else if ct.b8 > 0 && l < 256 {
e.e.encWr.writen2(ct.b8, uint8(l))
} else if l < 65536 {
e.e.encWr.writen1(ct.b16)
bigen.writeUint16(e.e.w(), uint16(l))
} else {
e.e.encWr.writen1(ct.b32)
bigen.writeUint32(e.e.w(), uint32(l))
}
}
//---------------------------------------------
type msgpackDecDriver struct {
decDriverNoopContainerReader
decDriverNoopNumberHelper
h *MsgpackHandle
bdAndBdread
_ bool
noBuiltInTypes
d Decoder
}
func (d *msgpackDecDriver) decoder() *Decoder {
return &d.d
}
// Note: This returns either a primitive (int, bool, etc) for non-containers,
// or a containerType, or a specific type denoting nil or extension.
// It is called when a nil interface{} is passed, leaving it up to the DecDriver
// to introspect the stream and decide how best to decode.
// It deciphers the value by looking at the stream first.
func (d *msgpackDecDriver) DecodeNaked() {
if !d.bdRead {
d.readNextBd()
}
bd := d.bd
n := d.d.naked()
var decodeFurther bool
switch bd {
case mpNil:
n.v = valueTypeNil
d.bdRead = false
case mpFalse:
n.v = valueTypeBool
n.b = false
case mpTrue:
n.v = valueTypeBool
n.b = true
case mpFloat:
n.v = valueTypeFloat
n.f = float64(math.Float32frombits(bigen.Uint32(d.d.decRd.readn4())))
case mpDouble:
n.v = valueTypeFloat
n.f = math.Float64frombits(bigen.Uint64(d.d.decRd.readn8()))
case mpUint8:
n.v = valueTypeUint
n.u = uint64(d.d.decRd.readn1())
case mpUint16:
n.v = valueTypeUint
n.u = uint64(bigen.Uint16(d.d.decRd.readn2()))
case mpUint32:
n.v = valueTypeUint
n.u = uint64(bigen.Uint32(d.d.decRd.readn4()))
case mpUint64:
n.v = valueTypeUint
n.u = uint64(bigen.Uint64(d.d.decRd.readn8()))
case mpInt8:
n.v = valueTypeInt
n.i = int64(int8(d.d.decRd.readn1()))
case mpInt16:
n.v = valueTypeInt
n.i = int64(int16(bigen.Uint16(d.d.decRd.readn2())))
case mpInt32:
n.v = valueTypeInt
n.i = int64(int32(bigen.Uint32(d.d.decRd.readn4())))
case mpInt64:
n.v = valueTypeInt
n.i = int64(int64(bigen.Uint64(d.d.decRd.readn8())))
default:
switch {
case bd >= mpPosFixNumMin && bd <= mpPosFixNumMax:
// positive fixnum (always signed)
n.v = valueTypeInt
n.i = int64(int8(bd))
case bd >= mpNegFixNumMin && bd <= mpNegFixNumMax:
// negative fixnum
n.v = valueTypeInt
n.i = int64(int8(bd))
case bd == mpStr8, bd == mpStr16, bd == mpStr32, bd >= mpFixStrMin && bd <= mpFixStrMax:
d.d.fauxUnionReadRawBytes(d.h.WriteExt)
// if d.h.WriteExt || d.h.RawToString {
// n.v = valueTypeString
// n.s = d.d.stringZC(d.DecodeStringAsBytes())
// } else {
// n.v = valueTypeBytes
// n.l = d.DecodeBytes([]byte{})
// }
case bd == mpBin8, bd == mpBin16, bd == mpBin32:
d.d.fauxUnionReadRawBytes(false)
case bd == mpArray16, bd == mpArray32, bd >= mpFixArrayMin && bd <= mpFixArrayMax:
n.v = valueTypeArray
decodeFurther = true
case bd == mpMap16, bd == mpMap32, bd >= mpFixMapMin && bd <= mpFixMapMax:
n.v = valueTypeMap
decodeFurther = true
case bd >= mpFixExt1 && bd <= mpFixExt16, bd >= mpExt8 && bd <= mpExt32:
n.v = valueTypeExt
clen := d.readExtLen()
n.u = uint64(d.d.decRd.readn1())
if n.u == uint64(mpTimeExtTagU) {
n.v = valueTypeTime
n.t = d.decodeTime(clen)
} else if d.d.bytes {
n.l = d.d.decRd.rb.readx(uint(clen))
} else {
n.l = decByteSlice(d.d.r(), clen, d.d.h.MaxInitLen, d.d.b[:])
}
default:
d.d.errorf("cannot infer value: %s: Ox%x/%d/%s", msgBadDesc, bd, bd, mpdesc(bd))
}
}
if !decodeFurther {
d.bdRead = false
}
if n.v == valueTypeUint && d.h.SignedInteger {
n.v = valueTypeInt
n.i = int64(n.u)
}
}
func (d *msgpackDecDriver) nextValueBytes(v0 []byte) (v []byte) {
if !d.bdRead {
d.readNextBd()
}
v = v0
var h = decNextValueBytesHelper{d: &d.d}
var cursor = d.d.rb.c - 1
h.append1(&v, d.bd)
v = d.nextValueBytesBdReadR(v)
d.bdRead = false
h.bytesRdV(&v, cursor)
return
}
func (d *msgpackDecDriver) nextValueBytesR(v0 []byte) (v []byte) {
d.readNextBd()
v = v0
var h = decNextValueBytesHelper{d: &d.d}
h.append1(&v, d.bd)
return d.nextValueBytesBdReadR(v)
}
func (d *msgpackDecDriver) nextValueBytesBdReadR(v0 []byte) (v []byte) {
v = v0
var h = decNextValueBytesHelper{d: &d.d}
bd := d.bd
var clen uint
switch bd {
case mpNil, mpFalse, mpTrue: // pass
case mpUint8, mpInt8:
h.append1(&v, d.d.decRd.readn1())
case mpUint16, mpInt16:
h.appendN(&v, d.d.decRd.readx(2)...)
case mpFloat, mpUint32, mpInt32:
h.appendN(&v, d.d.decRd.readx(4)...)
case mpDouble, mpUint64, mpInt64:
h.appendN(&v, d.d.decRd.readx(8)...)
case mpStr8, mpBin8:
clen = uint(d.d.decRd.readn1())
h.append1(&v, byte(clen))
h.appendN(&v, d.d.decRd.readx(clen)...)
case mpStr16, mpBin16:
x := d.d.decRd.readn2()
h.appendN(&v, x[:]...)
clen = uint(bigen.Uint16(x))
h.appendN(&v, d.d.decRd.readx(clen)...)
case mpStr32, mpBin32:
x := d.d.decRd.readn4()
h.appendN(&v, x[:]...)
clen = uint(bigen.Uint32(x))
h.appendN(&v, d.d.decRd.readx(clen)...)
case mpFixExt1:
h.append1(&v, d.d.decRd.readn1()) // tag
h.append1(&v, d.d.decRd.readn1())
case mpFixExt2:
h.append1(&v, d.d.decRd.readn1()) // tag
h.appendN(&v, d.d.decRd.readx(2)...)
case mpFixExt4:
h.append1(&v, d.d.decRd.readn1()) // tag
h.appendN(&v, d.d.decRd.readx(4)...)
case mpFixExt8:
h.append1(&v, d.d.decRd.readn1()) // tag
h.appendN(&v, d.d.decRd.readx(8)...)
case mpFixExt16:
h.append1(&v, d.d.decRd.readn1()) // tag
h.appendN(&v, d.d.decRd.readx(16)...)
case mpExt8:
clen = uint(d.d.decRd.readn1())
h.append1(&v, uint8(clen))
h.append1(&v, d.d.decRd.readn1()) // tag
h.appendN(&v, d.d.decRd.readx(clen)...)
case mpExt16:
x := d.d.decRd.readn2()
clen = uint(bigen.Uint16(x))
h.appendN(&v, x[:]...)
h.append1(&v, d.d.decRd.readn1()) // tag
h.appendN(&v, d.d.decRd.readx(clen)...)
case mpExt32:
x := d.d.decRd.readn4()
clen = uint(bigen.Uint32(x))
h.appendN(&v, x[:]...)
h.append1(&v, d.d.decRd.readn1()) // tag
h.appendN(&v, d.d.decRd.readx(clen)...)
case mpArray16:
x := d.d.decRd.readn2()
clen = uint(bigen.Uint16(x))
h.appendN(&v, x[:]...)
for i := uint(0); i < clen; i++ {
v = d.nextValueBytesR(v)
}
case mpArray32:
x := d.d.decRd.readn4()
clen = uint(bigen.Uint32(x))
h.appendN(&v, x[:]...)
for i := uint(0); i < clen; i++ {
v = d.nextValueBytesR(v)
}
case mpMap16:
x := d.d.decRd.readn2()
clen = uint(bigen.Uint16(x))
h.appendN(&v, x[:]...)
for i := uint(0); i < clen; i++ {
v = d.nextValueBytesR(v)
v = d.nextValueBytesR(v)
}
case mpMap32:
x := d.d.decRd.readn4()
clen = uint(bigen.Uint32(x))
h.appendN(&v, x[:]...)
for i := uint(0); i < clen; i++ {
v = d.nextValueBytesR(v)
v = d.nextValueBytesR(v)
}
default:
switch {
case bd >= mpPosFixNumMin && bd <= mpPosFixNumMax: // pass
case bd >= mpNegFixNumMin && bd <= mpNegFixNumMax: // pass
case bd >= mpFixStrMin && bd <= mpFixStrMax:
clen = uint(mpFixStrMin ^ bd)
h.appendN(&v, d.d.decRd.readx(clen)...)
case bd >= mpFixArrayMin && bd <= mpFixArrayMax:
clen = uint(mpFixArrayMin ^ bd)
for i := uint(0); i < clen; i++ {
v = d.nextValueBytesR(v)
}
case bd >= mpFixMapMin && bd <= mpFixMapMax:
clen = uint(mpFixMapMin ^ bd)
for i := uint(0); i < clen; i++ {
v = d.nextValueBytesR(v)
v = d.nextValueBytesR(v)
}
default:
d.d.errorf("nextValueBytes: cannot infer value: %s: Ox%x/%d/%s", msgBadDesc, bd, bd, mpdesc(bd))
}
}
return
}
func (d *msgpackDecDriver) decFloat4Int32() (f float32) {
fbits := bigen.Uint32(d.d.decRd.readn4())
f = math.Float32frombits(fbits)
if !noFrac32(fbits) {
d.d.errorf("assigning integer value from float32 with a fraction: %v", f)
}
return
}
func (d *msgpackDecDriver) decFloat4Int64() (f float64) {
fbits := bigen.Uint64(d.d.decRd.readn8())
f = math.Float64frombits(fbits)
if !noFrac64(fbits) {
d.d.errorf("assigning integer value from float64 with a fraction: %v", f)
}
return
}
// int can be decoded from msgpack type: intXXX or uintXXX
func (d *msgpackDecDriver) DecodeInt64() (i int64) {
if d.advanceNil() {
return
}
switch d.bd {
case mpUint8:
i = int64(uint64(d.d.decRd.readn1()))
case mpUint16:
i = int64(uint64(bigen.Uint16(d.d.decRd.readn2())))
case mpUint32:
i = int64(uint64(bigen.Uint32(d.d.decRd.readn4())))
case mpUint64:
i = int64(bigen.Uint64(d.d.decRd.readn8()))
case mpInt8:
i = int64(int8(d.d.decRd.readn1()))
case mpInt16:
i = int64(int16(bigen.Uint16(d.d.decRd.readn2())))
case mpInt32:
i = int64(int32(bigen.Uint32(d.d.decRd.readn4())))
case mpInt64:
i = int64(bigen.Uint64(d.d.decRd.readn8()))
case mpFloat:
i = int64(d.decFloat4Int32())
case mpDouble:
i = int64(d.decFloat4Int64())
default:
switch {
case d.bd >= mpPosFixNumMin && d.bd <= mpPosFixNumMax:
i = int64(int8(d.bd))
case d.bd >= mpNegFixNumMin && d.bd <= mpNegFixNumMax:
i = int64(int8(d.bd))
default:
d.d.errorf("cannot decode signed integer: %s: %x/%s", msgBadDesc, d.bd, mpdesc(d.bd))
}
}
d.bdRead = false
return
}
// uint can be decoded from msgpack type: intXXX or uintXXX
func (d *msgpackDecDriver) DecodeUint64() (ui uint64) {
if d.advanceNil() {
return
}
switch d.bd {
case mpUint8:
ui = uint64(d.d.decRd.readn1())
case mpUint16:
ui = uint64(bigen.Uint16(d.d.decRd.readn2()))
case mpUint32:
ui = uint64(bigen.Uint32(d.d.decRd.readn4()))
case mpUint64:
ui = bigen.Uint64(d.d.decRd.readn8())
case mpInt8:
if i := int64(int8(d.d.decRd.readn1())); i >= 0 {
ui = uint64(i)
} else {
d.d.errorf("assigning negative signed value: %v, to unsigned type", i)
}
case mpInt16:
if i := int64(int16(bigen.Uint16(d.d.decRd.readn2()))); i >= 0 {
ui = uint64(i)
} else {
d.d.errorf("assigning negative signed value: %v, to unsigned type", i)
}
case mpInt32:
if i := int64(int32(bigen.Uint32(d.d.decRd.readn4()))); i >= 0 {
ui = uint64(i)
} else {
d.d.errorf("assigning negative signed value: %v, to unsigned type", i)
}
case mpInt64:
if i := int64(bigen.Uint64(d.d.decRd.readn8())); i >= 0 {
ui = uint64(i)
} else {
d.d.errorf("assigning negative signed value: %v, to unsigned type", i)
}
case mpFloat:
if f := d.decFloat4Int32(); f >= 0 {
ui = uint64(f)
} else {
d.d.errorf("assigning negative float value: %v, to unsigned type", f)
}
case mpDouble:
if f := d.decFloat4Int64(); f >= 0 {
ui = uint64(f)
} else {
d.d.errorf("assigning negative float value: %v, to unsigned type", f)
}
default:
switch {
case d.bd >= mpPosFixNumMin && d.bd <= mpPosFixNumMax:
ui = uint64(d.bd)
case d.bd >= mpNegFixNumMin && d.bd <= mpNegFixNumMax:
d.d.errorf("assigning negative signed value: %v, to unsigned type", int(d.bd))
default:
d.d.errorf("cannot decode unsigned integer: %s: %x/%s", msgBadDesc, d.bd, mpdesc(d.bd))
}
}
d.bdRead = false
return
}
// float can either be decoded from msgpack type: float, double or intX
func (d *msgpackDecDriver) DecodeFloat64() (f float64) {
if d.advanceNil() {
return
}
if d.bd == mpFloat {
f = float64(math.Float32frombits(bigen.Uint32(d.d.decRd.readn4())))
} else if d.bd == mpDouble {
f = math.Float64frombits(bigen.Uint64(d.d.decRd.readn8()))
} else {
f = float64(d.DecodeInt64())
}
d.bdRead = false
return
}
// bool can be decoded from bool, fixnum 0 or 1.
func (d *msgpackDecDriver) DecodeBool() (b bool) {
if d.advanceNil() {
return
}
if d.bd == mpFalse || d.bd == 0 {
// b = false
} else if d.bd == mpTrue || d.bd == 1 {
b = true
} else {
d.d.errorf("cannot decode bool: %s: %x/%s", msgBadDesc, d.bd, mpdesc(d.bd))
}
d.bdRead = false
return
}
func (d *msgpackDecDriver) DecodeBytes(bs []byte) (bsOut []byte) {
d.d.decByteState = decByteStateNone
if d.advanceNil() {
return
}
bd := d.bd
var clen int
if bd == mpBin8 || bd == mpBin16 || bd == mpBin32 {
clen = d.readContainerLen(msgpackContainerBin) // binary
} else if bd == mpStr8 || bd == mpStr16 || bd == mpStr32 ||
(bd >= mpFixStrMin && bd <= mpFixStrMax) {
clen = d.readContainerLen(msgpackContainerStr) // string/raw
} else if bd == mpArray16 || bd == mpArray32 ||
(bd >= mpFixArrayMin && bd <= mpFixArrayMax) {
// check if an "array" of uint8's
if bs == nil {
d.d.decByteState = decByteStateReuseBuf
bs = d.d.b[:]
}
// bsOut, _ = fastpathTV.DecSliceUint8V(bs, true, d.d)
slen := d.ReadArrayStart()
var changed bool
if bs, changed = usableByteSlice(bs, slen); changed {
d.d.decByteState = decByteStateNone
}
for i := 0; i < len(bs); i++ {
bs[i] = uint8(chkOvf.UintV(d.DecodeUint64(), 8))
}
for i := len(bs); i < slen; i++ {
bs = append(bs, uint8(chkOvf.UintV(d.DecodeUint64(), 8)))
}
return bs
} else {
d.d.errorf("invalid byte descriptor for decoding bytes, got: 0x%x", d.bd)
}
d.bdRead = false
if d.d.zerocopy() {
d.d.decByteState = decByteStateZerocopy
return d.d.decRd.rb.readx(uint(clen))
}
if bs == nil {
d.d.decByteState = decByteStateReuseBuf
bs = d.d.b[:]
}
return decByteSlice(d.d.r(), clen, d.h.MaxInitLen, bs)
}
func (d *msgpackDecDriver) DecodeStringAsBytes() (s []byte) {
s = d.DecodeBytes(nil)
if d.h.ValidateUnicode && !utf8.Valid(s) {
d.d.errorf("DecodeStringAsBytes: invalid UTF-8: %s", s)
}
return
}
func (d *msgpackDecDriver) descBd() string {
return sprintf("%v (%s)", d.bd, mpdesc(d.bd))
}
func (d *msgpackDecDriver) readNextBd() {
d.bd = d.d.decRd.readn1()
d.bdRead = true
}
func (d *msgpackDecDriver) advanceNil() (null bool) {
if !d.bdRead {
d.readNextBd()
}
if d.bd == mpNil {
d.bdRead = false
return true // null = true
}
return
}
func (d *msgpackDecDriver) TryNil() (v bool) {
return d.advanceNil()
}
func (d *msgpackDecDriver) ContainerType() (vt valueType) {
if !d.bdRead {
d.readNextBd()
}
bd := d.bd
if bd == mpNil {
d.bdRead = false
return valueTypeNil
} else if bd == mpBin8 || bd == mpBin16 || bd == mpBin32 {
return valueTypeBytes
} else if bd == mpStr8 || bd == mpStr16 || bd == mpStr32 ||
(bd >= mpFixStrMin && bd <= mpFixStrMax) {
if d.h.WriteExt || d.h.RawToString { // UTF-8 string (new spec)
return valueTypeString
}
return valueTypeBytes // raw (old spec)
} else if bd == mpArray16 || bd == mpArray32 || (bd >= mpFixArrayMin && bd <= mpFixArrayMax) {
return valueTypeArray
} else if bd == mpMap16 || bd == mpMap32 || (bd >= mpFixMapMin && bd <= mpFixMapMax) {
return valueTypeMap
}
return valueTypeUnset
}
func (d *msgpackDecDriver) readContainerLen(ct msgpackContainerType) (clen int) {
bd := d.bd
if bd == ct.b8 {
clen = int(d.d.decRd.readn1())
} else if bd == ct.b16 {
clen = int(bigen.Uint16(d.d.decRd.readn2()))
} else if bd == ct.b32 {
clen = int(bigen.Uint32(d.d.decRd.readn4()))
} else if (ct.bFixMin & bd) == ct.bFixMin {
clen = int(ct.bFixMin ^ bd)
} else {
d.d.errorf("cannot read container length: %s: hex: %x, decimal: %d", msgBadDesc, bd, bd)
}
d.bdRead = false
return
}
func (d *msgpackDecDriver) ReadMapStart() int {
if d.advanceNil() {
return containerLenNil
}
return d.readContainerLen(msgpackContainerMap)
}
func (d *msgpackDecDriver) ReadArrayStart() int {
if d.advanceNil() {
return containerLenNil
}
return d.readContainerLen(msgpackContainerList)
}
func (d *msgpackDecDriver) readExtLen() (clen int) {
switch d.bd {
case mpFixExt1:
clen = 1
case mpFixExt2:
clen = 2
case mpFixExt4:
clen = 4
case mpFixExt8:
clen = 8
case mpFixExt16:
clen = 16
case mpExt8:
clen = int(d.d.decRd.readn1())
case mpExt16:
clen = int(bigen.Uint16(d.d.decRd.readn2()))
case mpExt32:
clen = int(bigen.Uint32(d.d.decRd.readn4()))
default:
d.d.errorf("decoding ext bytes: found unexpected byte: %x", d.bd)
}
return
}
func (d *msgpackDecDriver) DecodeTime() (t time.Time) {
// decode time from string bytes or ext
if d.advanceNil() {
return
}
bd := d.bd
var clen int
if bd == mpBin8 || bd == mpBin16 || bd == mpBin32 {
clen = d.readContainerLen(msgpackContainerBin) // binary
} else if bd == mpStr8 || bd == mpStr16 || bd == mpStr32 ||
(bd >= mpFixStrMin && bd <= mpFixStrMax) {
clen = d.readContainerLen(msgpackContainerStr) // string/raw
} else {
// expect to see mpFixExt4,-1 OR mpFixExt8,-1 OR mpExt8,12,-1
d.bdRead = false
b2 := d.d.decRd.readn1()
if d.bd == mpFixExt4 && b2 == mpTimeExtTagU {
clen = 4
} else if d.bd == mpFixExt8 && b2 == mpTimeExtTagU {
clen = 8
} else if d.bd == mpExt8 && b2 == 12 && d.d.decRd.readn1() == mpTimeExtTagU {
clen = 12
} else {
d.d.errorf("invalid stream for decoding time as extension: got 0x%x, 0x%x", d.bd, b2)
}
}
return d.decodeTime(clen)
}
func (d *msgpackDecDriver) decodeTime(clen int) (t time.Time) {
d.bdRead = false
switch clen {
case 4:
t = time.Unix(int64(bigen.Uint32(d.d.decRd.readn4())), 0).UTC()
case 8:
tv := bigen.Uint64(d.d.decRd.readn8())
t = time.Unix(int64(tv&0x00000003ffffffff), int64(tv>>34)).UTC()
case 12:
nsec := bigen.Uint32(d.d.decRd.readn4())
sec := bigen.Uint64(d.d.decRd.readn8())
t = time.Unix(int64(sec), int64(nsec)).UTC()
default:
d.d.errorf("invalid length of bytes for decoding time - expecting 4 or 8 or 12, got %d", clen)
}
return
}
func (d *msgpackDecDriver) DecodeExt(rv interface{}, basetype reflect.Type, xtag uint64, ext Ext) {
if xtag > 0xff {
d.d.errorf("ext: tag must be <= 0xff; got: %v", xtag)
}
if d.advanceNil() {
return
}
xbs, realxtag1, zerocopy := d.decodeExtV(ext != nil, uint8(xtag))
realxtag := uint64(realxtag1)
if ext == nil {
re := rv.(*RawExt)
re.Tag = realxtag
re.setData(xbs, zerocopy)
} else if ext == SelfExt {
d.d.sideDecode(rv, basetype, xbs)
} else {
ext.ReadExt(rv, xbs)
}
}
func (d *msgpackDecDriver) decodeExtV(verifyTag bool, tag byte) (xbs []byte, xtag byte, zerocopy bool) {
xbd := d.bd
if xbd == mpBin8 || xbd == mpBin16 || xbd == mpBin32 {
xbs = d.DecodeBytes(nil)
} else if xbd == mpStr8 || xbd == mpStr16 || xbd == mpStr32 ||
(xbd >= mpFixStrMin && xbd <= mpFixStrMax) {
xbs = d.DecodeStringAsBytes()
} else {
clen := d.readExtLen()
xtag = d.d.decRd.readn1()
if verifyTag && xtag != tag {
d.d.errorf("wrong extension tag - got %b, expecting %v", xtag, tag)
}
if d.d.bytes {
xbs = d.d.decRd.rb.readx(uint(clen))
zerocopy = true
} else {
xbs = decByteSlice(d.d.r(), clen, d.d.h.MaxInitLen, d.d.b[:])
}
}
d.bdRead = false
return
}
//--------------------------------------------------
// MsgpackHandle is a Handle for the Msgpack Schema-Free Encoding Format.
type MsgpackHandle struct {
binaryEncodingType
BasicHandle
// NoFixedNum says to output all signed integers as 2-bytes, never as 1-byte fixednum.
NoFixedNum bool
// WriteExt controls whether the new spec is honored.
//
// With WriteExt=true, we can encode configured extensions with extension tags
// and encode string/[]byte/extensions in a way compatible with the new spec
// but incompatible with the old spec.
//
// For compatibility with the old spec, set WriteExt=false.
//
// With WriteExt=false:
// configured extensions are serialized as raw bytes (not msgpack extensions).
// reserved byte descriptors like Str8 and those enabling the new msgpack Binary type
// are not encoded.
WriteExt bool
// PositiveIntUnsigned says to encode positive integers as unsigned.
PositiveIntUnsigned bool
}
// Name returns the name of the handle: msgpack
func (h *MsgpackHandle) Name() string { return "msgpack" }
func (h *MsgpackHandle) desc(bd byte) string { return mpdesc(bd) }
func (h *MsgpackHandle) newEncDriver() encDriver {
var e = &msgpackEncDriver{h: h}
e.e.e = e
e.e.init(h)
e.reset()
return e
}
func (h *MsgpackHandle) newDecDriver() decDriver {
d := &msgpackDecDriver{h: h}
d.d.d = d
d.d.init(h)
d.reset()
return d
}
//--------------------------------------------------
type msgpackSpecRpcCodec struct {
rpcCodec
}
// /////////////// Spec RPC Codec ///////////////////
func (c *msgpackSpecRpcCodec) WriteRequest(r *rpc.Request, body interface{}) error {
// WriteRequest can write to both a Go service, and other services that do
// not abide by the 1 argument rule of a Go service.
// We discriminate based on if the body is a MsgpackSpecRpcMultiArgs
var bodyArr []interface{}
if m, ok := body.(MsgpackSpecRpcMultiArgs); ok {
bodyArr = ([]interface{})(m)
} else {
bodyArr = []interface{}{body}
}
r2 := []interface{}{0, uint32(r.Seq), r.ServiceMethod, bodyArr}
return c.write(r2)
}
func (c *msgpackSpecRpcCodec) WriteResponse(r *rpc.Response, body interface{}) error {
var moe interface{}
if r.Error != "" {
moe = r.Error
}
if moe != nil && body != nil {
body = nil
}
r2 := []interface{}{1, uint32(r.Seq), moe, body}
return c.write(r2)
}
func (c *msgpackSpecRpcCodec) ReadResponseHeader(r *rpc.Response) error {
return c.parseCustomHeader(1, &r.Seq, &r.Error)
}
func (c *msgpackSpecRpcCodec) ReadRequestHeader(r *rpc.Request) error {
return c.parseCustomHeader(0, &r.Seq, &r.ServiceMethod)
}
func (c *msgpackSpecRpcCodec) ReadRequestBody(body interface{}) error {
if body == nil { // read and discard
return c.read(nil)
}
bodyArr := []interface{}{body}
return c.read(&bodyArr)
}
func (c *msgpackSpecRpcCodec) parseCustomHeader(expectTypeByte byte, msgid *uint64, methodOrError *string) (err error) {
if cls := c.cls.load(); cls.closed {
return io.ErrUnexpectedEOF
}
// We read the response header by hand
// so that the body can be decoded on its own from the stream at a later time.
const fia byte = 0x94 //four item array descriptor value
var ba [1]byte
var n int
for {
n, err = c.r.Read(ba[:])
if err != nil {
return
}
if n == 1 {
break
}
}
var b = ba[0]
if b != fia {
err = fmt.Errorf("not array - %s %x/%s", msgBadDesc, b, mpdesc(b))
} else {
err = c.read(&b)
if err == nil {
if b != expectTypeByte {
err = fmt.Errorf("%s - expecting %v but got %x/%s", msgBadDesc, expectTypeByte, b, mpdesc(b))
} else {
err = c.read(msgid)
if err == nil {
err = c.read(methodOrError)
}
}
}
}
return
}
//--------------------------------------------------
// msgpackSpecRpc is the implementation of Rpc that uses custom communication protocol
// as defined in the msgpack spec at https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md
type msgpackSpecRpc struct{}
// MsgpackSpecRpc implements Rpc using the communication protocol defined in
// the msgpack spec at https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md .
//
// See GoRpc documentation, for information on buffering for better performance.
var MsgpackSpecRpc msgpackSpecRpc
func (x msgpackSpecRpc) ServerCodec(conn io.ReadWriteCloser, h Handle) rpc.ServerCodec {
return &msgpackSpecRpcCodec{newRPCCodec(conn, h)}
}
func (x msgpackSpecRpc) ClientCodec(conn io.ReadWriteCloser, h Handle) rpc.ClientCodec {
return &msgpackSpecRpcCodec{newRPCCodec(conn, h)}
}
var _ decDriver = (*msgpackDecDriver)(nil)
var _ encDriver = (*msgpackEncDriver)(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/ugorji/go/codec/helper_internal.go | vendor/github.com/ugorji/go/codec/helper_internal.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
package codec
// maxArrayLen is the size of uint, which determines
// the maximum length of any array.
const maxArrayLen = 1<<((32<<(^uint(0)>>63))-1) - 1
// All non-std package dependencies live in this file,
// so porting to different environment is easy (just update functions).
func pruneSignExt(v []byte, pos bool) (n int) {
if len(v) < 2 {
} else if pos && v[0] == 0 {
for ; v[n] == 0 && n+1 < len(v) && (v[n+1]&(1<<7) == 0); n++ {
}
} else if !pos && v[0] == 0xff {
for ; v[n] == 0xff && n+1 < len(v) && (v[n+1]&(1<<7) != 0); n++ {
}
}
return
}
func halfFloatToFloatBits(h uint16) (f uint32) {
// retrofitted from:
// - OGRE (Object-Oriented Graphics Rendering Engine)
// function: halfToFloatI https://www.ogre3d.org/docs/api/1.9/_ogre_bitwise_8h_source.html
s := uint32(h >> 15)
m := uint32(h & 0x03ff)
e := int32((h >> 10) & 0x1f)
if e == 0 {
if m == 0 { // plus or minus 0
return s << 31
}
// Denormalized number -- renormalize it
for (m & 0x0400) == 0 {
m <<= 1
e -= 1
}
e += 1
m &= ^uint32(0x0400)
} else if e == 31 {
if m == 0 { // Inf
return (s << 31) | 0x7f800000
}
return (s << 31) | 0x7f800000 | (m << 13) // NaN
}
e = e + (127 - 15)
m = m << 13
return (s << 31) | (uint32(e) << 23) | m
}
func floatToHalfFloatBits(i uint32) (h uint16) {
// retrofitted from:
// - OGRE (Object-Oriented Graphics Rendering Engine)
// function: halfToFloatI https://www.ogre3d.org/docs/api/1.9/_ogre_bitwise_8h_source.html
// - http://www.java2s.com/example/java-utility-method/float-to/floattohalf-float-f-fae00.html
s := (i >> 16) & 0x8000
e := int32(((i >> 23) & 0xff) - (127 - 15))
m := i & 0x7fffff
var h32 uint32
if e <= 0 {
if e < -10 { // zero
h32 = s // track -0 vs +0
} else {
m = (m | 0x800000) >> uint32(1-e)
h32 = s | (m >> 13)
}
} else if e == 0xff-(127-15) {
if m == 0 { // Inf
h32 = s | 0x7c00
} else { // NAN
m >>= 13
var me uint32
if m == 0 {
me = 1
}
h32 = s | 0x7c00 | m | me
}
} else {
if e > 30 { // Overflow
h32 = s | 0x7c00
} else {
h32 = s | (uint32(e) << 10) | (m >> 13)
}
}
h = uint16(h32)
return
}
// growCap will return a new capacity for a slice, given the following:
// - oldCap: current capacity
// - unit: in-memory size of an element
// - num: number of elements to add
func growCap(oldCap, unit, num uint) (newCap uint) {
// appendslice logic (if cap < 1024, *2, else *1.25):
// leads to many copy calls, especially when copying bytes.
// bytes.Buffer model (2*cap + n): much better for bytes.
// smarter way is to take the byte-size of the appended element(type) into account
// maintain 1 thresholds:
// t1: if cap <= t1, newcap = 2x
// else newcap = 1.5x
//
// t1 is always >= 1024.
// This means that, if unit size >= 16, then always do 2x or 1.5x (ie t1, t2, t3 are all same)
//
// With this, appending for bytes increase by:
// 100% up to 4K
// 50% beyond that
// unit can be 0 e.g. for struct{}{}; handle that appropriately
maxCap := num + (oldCap * 3 / 2)
if unit == 0 || maxCap > maxArrayLen || maxCap < oldCap { // handle wraparound, etc
return maxArrayLen
}
var t1 uint = 1024 // default thresholds for large values
if unit <= 4 {
t1 = 8 * 1024
} else if unit <= 16 {
t1 = 2 * 1024
}
newCap = 2 + num
if oldCap > 0 {
if oldCap <= t1 { // [0,t1]
newCap = num + (oldCap * 2)
} else { // (t1,infinity]
newCap = maxCap
}
}
// ensure newCap takes multiples of a cache line (size is a multiple of 64)
t1 = newCap * unit
if t2 := t1 % 64; t2 != 0 {
t1 += 64 - t2
newCap = t1 / unit
}
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/ugorji/go/codec/helper_not_unsafe.go | vendor/github.com/ugorji/go/codec/helper_not_unsafe.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
//go:build !go1.9 || safe || codec.safe || appengine
// +build !go1.9 safe codec.safe appengine
package codec
import (
// "hash/adler32"
"math"
"reflect"
"sync/atomic"
"time"
)
// This file has safe variants of some helper functions.
// MARKER: See helper_unsafe.go for the usage documentation.
const safeMode = true
const transientSizeMax = 0
const transientValueHasStringSlice = true
func byteAt(b []byte, index uint) byte {
return b[index]
}
func setByteAt(b []byte, index uint, val byte) {
b[index] = val
}
func byteSliceOf(b []byte, start, end uint) []byte {
return b[start:end]
}
// func byteSliceWithLen(b []byte, length uint) []byte {
// return b[:length]
// }
func stringView(v []byte) string {
return string(v)
}
func bytesView(v string) []byte {
return []byte(v)
}
func byteSliceSameData(v1 []byte, v2 []byte) bool {
return cap(v1) != 0 && cap(v2) != 0 && &(v1[:1][0]) == &(v2[:1][0])
}
func okBytes2(b []byte) (v [2]byte) {
copy(v[:], b)
return
}
func okBytes3(b []byte) (v [3]byte) {
copy(v[:], b)
return
}
func okBytes4(b []byte) (v [4]byte) {
copy(v[:], b)
return
}
func okBytes8(b []byte) (v [8]byte) {
copy(v[:], b)
return
}
func isNil(v interface{}) (rv reflect.Value, isnil bool) {
rv = reflect.ValueOf(v)
if isnilBitset.isset(byte(rv.Kind())) {
isnil = rv.IsNil()
}
return
}
func eq4i(i0, i1 interface{}) bool {
return i0 == i1
}
func rv4iptr(i interface{}) reflect.Value { return reflect.ValueOf(i) }
func rv4istr(i interface{}) reflect.Value { return reflect.ValueOf(i) }
// func rv4i(i interface{}) reflect.Value { return reflect.ValueOf(i) }
// func rv4iK(i interface{}, kind byte, isref bool) reflect.Value { return reflect.ValueOf(i) }
func rv2i(rv reflect.Value) interface{} {
return rv.Interface()
}
func rvAddr(rv reflect.Value, ptrType reflect.Type) reflect.Value {
return rv.Addr()
}
func rvIsNil(rv reflect.Value) bool {
return rv.IsNil()
}
func rvSetSliceLen(rv reflect.Value, length int) {
rv.SetLen(length)
}
func rvZeroAddrK(t reflect.Type, k reflect.Kind) reflect.Value {
return reflect.New(t).Elem()
}
func rvZeroK(t reflect.Type, k reflect.Kind) reflect.Value {
return reflect.Zero(t)
}
func rvConvert(v reflect.Value, t reflect.Type) (rv reflect.Value) {
// Note that reflect.Value.Convert(...) will make a copy if it is addressable.
// Since we decode into the passed value, we must try to convert the addressable value..
if v.CanAddr() {
return v.Addr().Convert(reflect.PtrTo(t)).Elem()
}
return v.Convert(t)
}
func rt2id(rt reflect.Type) uintptr {
return reflect.ValueOf(rt).Pointer()
}
func i2rtid(i interface{}) uintptr {
return reflect.ValueOf(reflect.TypeOf(i)).Pointer()
}
// --------------------------
func isEmptyValue(v reflect.Value, tinfos *TypeInfos, recursive bool) bool {
switch v.Kind() {
case reflect.Invalid:
return true
case reflect.String:
return v.Len() == 0
case reflect.Array:
// zero := reflect.Zero(v.Type().Elem())
// can I just check if the whole value is equal to zeros? seems not.
// can I just check if the whole value is equal to its zero value? no.
// Well, then we check if each value is empty without recursive.
for i, vlen := 0, v.Len(); i < vlen; i++ {
if !isEmptyValue(v.Index(i), tinfos, false) {
return false
}
}
return true
case reflect.Map, reflect.Slice, reflect.Chan:
return v.IsNil() || 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.Complex64, reflect.Complex128:
c := v.Complex()
return math.Float64bits(real(c)) == 0 && math.Float64bits(imag(c)) == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.Func, reflect.UnsafePointer:
return v.IsNil()
case reflect.Interface, reflect.Ptr:
isnil := v.IsNil()
if recursive && !isnil {
return isEmptyValue(v.Elem(), tinfos, recursive)
}
return isnil
case reflect.Struct:
return isEmptyStruct(v, tinfos, recursive)
}
return false
}
// isEmptyStruct is only called from isEmptyValue, and checks if a struct is empty:
// - does it implement IsZero() bool
// - is it comparable, and can i compare directly using ==
// - if checkStruct, then walk through the encodable fields
// and check if they are empty or not.
func isEmptyStruct(v reflect.Value, tinfos *TypeInfos, recursive bool) bool {
// v is a struct kind - no need to check again.
// We only check isZero on a struct kind, to reduce the amount of times
// that we lookup the rtid and typeInfo for each type as we walk the tree.
vt := v.Type()
rtid := rt2id(vt)
if tinfos == nil {
tinfos = defTypeInfos
}
ti := tinfos.get(rtid, vt)
if ti.rtid == timeTypId {
return rv2i(v).(time.Time).IsZero()
}
if ti.flagIsZeroer {
return rv2i(v).(isZeroer).IsZero()
}
if ti.flagIsZeroerPtr && v.CanAddr() {
return rv2i(v.Addr()).(isZeroer).IsZero()
}
if ti.flagIsCodecEmptyer {
return rv2i(v).(isCodecEmptyer).IsCodecEmpty()
}
if ti.flagIsCodecEmptyerPtr && v.CanAddr() {
return rv2i(v.Addr()).(isCodecEmptyer).IsCodecEmpty()
}
if ti.flagComparable {
return rv2i(v) == rv2i(rvZeroK(vt, reflect.Struct))
}
if !recursive {
return false
}
// We only care about what we can encode/decode,
// so that is what we use to check omitEmpty.
for _, si := range ti.sfi.source() {
sfv := si.path.field(v)
if sfv.IsValid() && !isEmptyValue(sfv, tinfos, recursive) {
return false
}
}
return true
}
// --------------------------
type perTypeElem struct {
t reflect.Type
rtid uintptr
zero reflect.Value
addr [2]reflect.Value
}
func (x *perTypeElem) get(index uint8) (v reflect.Value) {
v = x.addr[index%2]
if v.IsValid() {
v.Set(x.zero)
} else {
v = reflect.New(x.t).Elem()
x.addr[index%2] = v
}
return
}
type perType struct {
v []perTypeElem
}
type decPerType struct {
perType
}
type encPerType struct {
perType
}
func (x *perType) elem(t reflect.Type) *perTypeElem {
rtid := rt2id(t)
var h, i uint
var j = uint(len(x.v))
LOOP:
if i < j {
h = (i + j) >> 1 // avoid overflow when computing h // h = i + (j-i)/2
if x.v[h].rtid < rtid {
i = h + 1
} else {
j = h
}
goto LOOP
}
if i < uint(len(x.v)) {
if x.v[i].rtid != rtid {
x.v = append(x.v, perTypeElem{})
copy(x.v[i+1:], x.v[i:])
x.v[i] = perTypeElem{t: t, rtid: rtid, zero: reflect.Zero(t)}
}
} else {
x.v = append(x.v, perTypeElem{t: t, rtid: rtid, zero: reflect.Zero(t)})
}
return &x.v[i]
}
func (x *perType) TransientAddrK(t reflect.Type, k reflect.Kind) (rv reflect.Value) {
return x.elem(t).get(0)
}
func (x *perType) TransientAddr2K(t reflect.Type, k reflect.Kind) (rv reflect.Value) {
return x.elem(t).get(1)
}
func (x *perType) AddressableRO(v reflect.Value) (rv reflect.Value) {
rv = x.elem(v.Type()).get(0)
rvSetDirect(rv, v)
return
}
// --------------------------
type structFieldInfos struct {
c []*structFieldInfo
s []*structFieldInfo
}
func (x *structFieldInfos) load(source, sorted []*structFieldInfo) {
x.c = source
x.s = sorted
}
func (x *structFieldInfos) sorted() (v []*structFieldInfo) { return x.s }
func (x *structFieldInfos) source() (v []*structFieldInfo) { return x.c }
type atomicClsErr struct {
v atomic.Value
}
func (x *atomicClsErr) load() (e clsErr) {
if i := x.v.Load(); i != nil {
e = i.(clsErr)
}
return
}
func (x *atomicClsErr) store(p clsErr) {
x.v.Store(p)
}
// --------------------------
type atomicTypeInfoSlice struct {
v atomic.Value
}
func (x *atomicTypeInfoSlice) load() (e []rtid2ti) {
if i := x.v.Load(); i != nil {
e = i.([]rtid2ti)
}
return
}
func (x *atomicTypeInfoSlice) store(p []rtid2ti) {
x.v.Store(p)
}
// --------------------------
type atomicRtidFnSlice struct {
v atomic.Value
}
func (x *atomicRtidFnSlice) load() (e []codecRtidFn) {
if i := x.v.Load(); i != nil {
e = i.([]codecRtidFn)
}
return
}
func (x *atomicRtidFnSlice) store(p []codecRtidFn) {
x.v.Store(p)
}
// --------------------------
func (n *fauxUnion) ru() reflect.Value {
return reflect.ValueOf(&n.u).Elem()
}
func (n *fauxUnion) ri() reflect.Value {
return reflect.ValueOf(&n.i).Elem()
}
func (n *fauxUnion) rf() reflect.Value {
return reflect.ValueOf(&n.f).Elem()
}
func (n *fauxUnion) rl() reflect.Value {
return reflect.ValueOf(&n.l).Elem()
}
func (n *fauxUnion) rs() reflect.Value {
return reflect.ValueOf(&n.s).Elem()
}
func (n *fauxUnion) rt() reflect.Value {
return reflect.ValueOf(&n.t).Elem()
}
func (n *fauxUnion) rb() reflect.Value {
return reflect.ValueOf(&n.b).Elem()
}
// --------------------------
func rvSetBytes(rv reflect.Value, v []byte) {
rv.SetBytes(v)
}
func rvSetString(rv reflect.Value, v string) {
rv.SetString(v)
}
func rvSetBool(rv reflect.Value, v bool) {
rv.SetBool(v)
}
func rvSetTime(rv reflect.Value, v time.Time) {
rv.Set(reflect.ValueOf(v))
}
func rvSetFloat32(rv reflect.Value, v float32) {
rv.SetFloat(float64(v))
}
func rvSetFloat64(rv reflect.Value, v float64) {
rv.SetFloat(v)
}
func rvSetComplex64(rv reflect.Value, v complex64) {
rv.SetComplex(complex128(v))
}
func rvSetComplex128(rv reflect.Value, v complex128) {
rv.SetComplex(v)
}
func rvSetInt(rv reflect.Value, v int) {
rv.SetInt(int64(v))
}
func rvSetInt8(rv reflect.Value, v int8) {
rv.SetInt(int64(v))
}
func rvSetInt16(rv reflect.Value, v int16) {
rv.SetInt(int64(v))
}
func rvSetInt32(rv reflect.Value, v int32) {
rv.SetInt(int64(v))
}
func rvSetInt64(rv reflect.Value, v int64) {
rv.SetInt(v)
}
func rvSetUint(rv reflect.Value, v uint) {
rv.SetUint(uint64(v))
}
func rvSetUintptr(rv reflect.Value, v uintptr) {
rv.SetUint(uint64(v))
}
func rvSetUint8(rv reflect.Value, v uint8) {
rv.SetUint(uint64(v))
}
func rvSetUint16(rv reflect.Value, v uint16) {
rv.SetUint(uint64(v))
}
func rvSetUint32(rv reflect.Value, v uint32) {
rv.SetUint(uint64(v))
}
func rvSetUint64(rv reflect.Value, v uint64) {
rv.SetUint(v)
}
// ----------------
func rvSetDirect(rv reflect.Value, v reflect.Value) {
rv.Set(v)
}
func rvSetDirectZero(rv reflect.Value) {
rv.Set(reflect.Zero(rv.Type()))
}
// func rvSet(rv reflect.Value, v reflect.Value) {
// rv.Set(v)
// }
func rvSetIntf(rv reflect.Value, v reflect.Value) {
rv.Set(v)
}
func rvSetZero(rv reflect.Value) {
rv.Set(reflect.Zero(rv.Type()))
}
func rvSlice(rv reflect.Value, length int) reflect.Value {
return rv.Slice(0, length)
}
func rvMakeSlice(rv reflect.Value, ti *typeInfo, xlen, xcap int) (v reflect.Value, set bool) {
v = reflect.MakeSlice(ti.rt, xlen, xcap)
if rv.Len() > 0 {
reflect.Copy(v, rv)
}
return
}
func rvGrowSlice(rv reflect.Value, ti *typeInfo, cap, incr int) (v reflect.Value, newcap int, set bool) {
newcap = int(growCap(uint(cap), uint(ti.elemsize), uint(incr)))
v = reflect.MakeSlice(ti.rt, newcap, newcap)
if rv.Len() > 0 {
reflect.Copy(v, rv)
}
return
}
// ----------------
func rvSliceIndex(rv reflect.Value, i int, ti *typeInfo) reflect.Value {
return rv.Index(i)
}
func rvArrayIndex(rv reflect.Value, i int, ti *typeInfo) reflect.Value {
return rv.Index(i)
}
func rvSliceZeroCap(t reflect.Type) (v reflect.Value) {
return reflect.MakeSlice(t, 0, 0)
}
func rvLenSlice(rv reflect.Value) int {
return rv.Len()
}
func rvCapSlice(rv reflect.Value) int {
return rv.Cap()
}
func rvGetArrayBytes(rv reflect.Value, scratch []byte) (bs []byte) {
l := rv.Len()
if scratch == nil || rv.CanAddr() {
return rv.Slice(0, l).Bytes()
}
if l <= cap(scratch) {
bs = scratch[:l]
} else {
bs = make([]byte, l)
}
reflect.Copy(reflect.ValueOf(bs), rv)
return
}
func rvGetArray4Slice(rv reflect.Value) (v reflect.Value) {
v = rvZeroAddrK(reflectArrayOf(rvLenSlice(rv), rv.Type().Elem()), reflect.Array)
reflect.Copy(v, rv)
return
}
func rvGetSlice4Array(rv reflect.Value, v interface{}) {
// v is a pointer to a slice to be populated
// rv.Slice fails if address is not addressable, which can occur during encoding.
// Consequently, check if non-addressable, and if so, make new slice and copy into it first.
// MARKER: this *may* cause allocation if non-addressable, unfortunately.
rve := reflect.ValueOf(v).Elem()
l := rv.Len()
if rv.CanAddr() {
rve.Set(rv.Slice(0, l))
} else {
rvs := reflect.MakeSlice(rve.Type(), l, l)
reflect.Copy(rvs, rv)
rve.Set(rvs)
}
// reflect.ValueOf(v).Elem().Set(rv.Slice(0, rv.Len()))
}
func rvCopySlice(dest, src reflect.Value, _ reflect.Type) {
reflect.Copy(dest, src)
}
// ------------
func rvGetBool(rv reflect.Value) bool {
return rv.Bool()
}
func rvGetBytes(rv reflect.Value) []byte {
return rv.Bytes()
}
func rvGetTime(rv reflect.Value) time.Time {
return rv2i(rv).(time.Time)
}
func rvGetString(rv reflect.Value) string {
return rv.String()
}
func rvGetFloat64(rv reflect.Value) float64 {
return rv.Float()
}
func rvGetFloat32(rv reflect.Value) float32 {
return float32(rv.Float())
}
func rvGetComplex64(rv reflect.Value) complex64 {
return complex64(rv.Complex())
}
func rvGetComplex128(rv reflect.Value) complex128 {
return rv.Complex()
}
func rvGetInt(rv reflect.Value) int {
return int(rv.Int())
}
func rvGetInt8(rv reflect.Value) int8 {
return int8(rv.Int())
}
func rvGetInt16(rv reflect.Value) int16 {
return int16(rv.Int())
}
func rvGetInt32(rv reflect.Value) int32 {
return int32(rv.Int())
}
func rvGetInt64(rv reflect.Value) int64 {
return rv.Int()
}
func rvGetUint(rv reflect.Value) uint {
return uint(rv.Uint())
}
func rvGetUint8(rv reflect.Value) uint8 {
return uint8(rv.Uint())
}
func rvGetUint16(rv reflect.Value) uint16 {
return uint16(rv.Uint())
}
func rvGetUint32(rv reflect.Value) uint32 {
return uint32(rv.Uint())
}
func rvGetUint64(rv reflect.Value) uint64 {
return rv.Uint()
}
func rvGetUintptr(rv reflect.Value) uintptr {
return uintptr(rv.Uint())
}
func rvLenMap(rv reflect.Value) int {
return rv.Len()
}
// func copybytes(to, from []byte) int {
// return copy(to, from)
// }
// func copybytestr(to []byte, from string) int {
// return copy(to, from)
// }
// func rvLenArray(rv reflect.Value) int { return rv.Len() }
// ------------ map range and map indexing ----------
func mapStoresElemIndirect(elemsize uintptr) bool { return false }
func mapSet(m, k, v reflect.Value, keyFastKind mapKeyFastKind, _, _ bool) {
m.SetMapIndex(k, v)
}
func mapGet(m, k, v reflect.Value, keyFastKind mapKeyFastKind, _, _ bool) (vv reflect.Value) {
return m.MapIndex(k)
}
// func mapDelete(m, k reflect.Value) {
// m.SetMapIndex(k, reflect.Value{})
// }
func mapAddrLoopvarRV(t reflect.Type, k reflect.Kind) (r reflect.Value) {
return // reflect.New(t).Elem()
}
// ---------- ENCODER optimized ---------------
func (e *Encoder) jsondriver() *jsonEncDriver {
return e.e.(*jsonEncDriver)
}
// ---------- DECODER optimized ---------------
func (d *Decoder) jsondriver() *jsonDecDriver {
return d.d.(*jsonDecDriver)
}
func (d *Decoder) stringZC(v []byte) (s string) {
return d.string(v)
}
func (d *Decoder) mapKeyString(callFnRvk *bool, kstrbs, kstr2bs *[]byte) string {
return d.string(*kstr2bs)
}
// ---------- structFieldInfo optimized ---------------
func (n *structFieldInfoPathNode) rvField(v reflect.Value) reflect.Value {
return v.Field(int(n.index))
}
// ---------- others ---------------
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ugorji/go/codec/sort-slice.generated.go | vendor/github.com/ugorji/go/codec/sort-slice.generated.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
// Code generated from sort-slice.go.tmpl - DO NOT EDIT.
package codec
import (
"bytes"
"reflect"
"time"
)
type stringSlice []string
func (p stringSlice) Len() int { return len(p) }
func (p stringSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] }
func (p stringSlice) Less(i, j int) bool {
return p[uint(i)] < p[uint(j)]
}
type uint8Slice []uint8
func (p uint8Slice) Len() int { return len(p) }
func (p uint8Slice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] }
func (p uint8Slice) Less(i, j int) bool {
return p[uint(i)] < p[uint(j)]
}
type uint64Slice []uint64
func (p uint64Slice) Len() int { return len(p) }
func (p uint64Slice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] }
func (p uint64Slice) Less(i, j int) bool {
return p[uint(i)] < p[uint(j)]
}
type intSlice []int
func (p intSlice) Len() int { return len(p) }
func (p intSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] }
func (p intSlice) Less(i, j int) bool {
return p[uint(i)] < p[uint(j)]
}
type int32Slice []int32
func (p int32Slice) Len() int { return len(p) }
func (p int32Slice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] }
func (p int32Slice) Less(i, j int) bool {
return p[uint(i)] < p[uint(j)]
}
type stringRv struct {
v string
r reflect.Value
}
type stringRvSlice []stringRv
func (p stringRvSlice) Len() int { return len(p) }
func (p stringRvSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] }
func (p stringRvSlice) Less(i, j int) bool {
return p[uint(i)].v < p[uint(j)].v
}
type stringIntf struct {
v string
i interface{}
}
type stringIntfSlice []stringIntf
func (p stringIntfSlice) Len() int { return len(p) }
func (p stringIntfSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] }
func (p stringIntfSlice) Less(i, j int) bool {
return p[uint(i)].v < p[uint(j)].v
}
type float64Rv struct {
v float64
r reflect.Value
}
type float64RvSlice []float64Rv
func (p float64RvSlice) Len() int { return len(p) }
func (p float64RvSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] }
func (p float64RvSlice) Less(i, j int) bool {
return p[uint(i)].v < p[uint(j)].v || isNaN64(p[uint(i)].v) && !isNaN64(p[uint(j)].v)
}
type uint64Rv struct {
v uint64
r reflect.Value
}
type uint64RvSlice []uint64Rv
func (p uint64RvSlice) Len() int { return len(p) }
func (p uint64RvSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] }
func (p uint64RvSlice) Less(i, j int) bool {
return p[uint(i)].v < p[uint(j)].v
}
type int64Rv struct {
v int64
r reflect.Value
}
type int64RvSlice []int64Rv
func (p int64RvSlice) Len() int { return len(p) }
func (p int64RvSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] }
func (p int64RvSlice) Less(i, j int) bool {
return p[uint(i)].v < p[uint(j)].v
}
type timeRv struct {
v time.Time
r reflect.Value
}
type timeRvSlice []timeRv
func (p timeRvSlice) Len() int { return len(p) }
func (p timeRvSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] }
func (p timeRvSlice) Less(i, j int) bool {
return p[uint(i)].v.Before(p[uint(j)].v)
}
type bytesRv struct {
v []byte
r reflect.Value
}
type bytesRvSlice []bytesRv
func (p bytesRvSlice) Len() int { return len(p) }
func (p bytesRvSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] }
func (p bytesRvSlice) Less(i, j int) bool {
return bytes.Compare(p[uint(i)].v, p[uint(j)].v) == -1
}
type bytesIntf struct {
v []byte
i interface{}
}
type bytesIntfSlice []bytesIntf
func (p bytesIntfSlice) Len() int { return len(p) }
func (p bytesIntfSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] }
func (p bytesIntfSlice) Less(i, j int) bool {
return bytes.Compare(p[uint(i)].v, p[uint(j)].v) == -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/ugorji/go/codec/fast-path.not.go | vendor/github.com/ugorji/go/codec/fast-path.not.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
//go:build notfastpath || codec.notfastpath
// +build notfastpath codec.notfastpath
package codec
import "reflect"
const fastpathEnabled = false
// The generated fast-path code is very large, and adds a few seconds to the build time.
// This causes test execution, execution of small tools which use codec, etc
// to take a long time.
//
// To mitigate, we now support the notfastpath tag.
// This tag disables fastpath during build, allowing for faster build, test execution,
// short-program runs, etc.
func fastpathDecodeTypeSwitch(iv interface{}, d *Decoder) bool { return false }
func fastpathEncodeTypeSwitch(iv interface{}, e *Encoder) bool { return false }
// func fastpathEncodeTypeSwitchSlice(iv interface{}, e *Encoder) bool { return false }
// func fastpathEncodeTypeSwitchMap(iv interface{}, e *Encoder) bool { return false }
func fastpathDecodeSetZeroTypeSwitch(iv interface{}) bool { return false }
type fastpathT struct{}
type fastpathE struct {
rtid uintptr
rt reflect.Type
encfn func(*Encoder, *codecFnInfo, reflect.Value)
decfn func(*Decoder, *codecFnInfo, reflect.Value)
}
type fastpathA [0]fastpathE
func fastpathAvIndex(rtid uintptr) int { return -1 }
var fastpathAv fastpathA
var fastpathTV fastpathT
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ugorji/go/codec/writer.go | vendor/github.com/ugorji/go/codec/writer.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
package codec
import "io"
// encWriter abstracts writing to a byte array or to an io.Writer.
type encWriter interface {
writeb([]byte)
writestr(string)
writeqstr(string) // write string wrapped in quotes ie "..."
writen1(byte)
// add convenience functions for writing 2,4
writen2(byte, byte)
writen4([4]byte)
writen8([8]byte)
end()
}
// ---------------------------------------------
type bufioEncWriter struct {
w io.Writer
buf []byte
n int
b [16]byte // scratch buffer and padding (cache-aligned)
}
func (z *bufioEncWriter) reset(w io.Writer, bufsize int, blist *bytesFreelist) {
z.w = w
z.n = 0
if bufsize <= 0 {
bufsize = defEncByteBufSize
}
// bufsize must be >= 8, to accomodate writen methods (where n <= 8)
if bufsize <= 8 {
bufsize = 8
}
if cap(z.buf) < bufsize {
if len(z.buf) > 0 && &z.buf[0] != &z.b[0] {
blist.put(z.buf)
}
if len(z.b) > bufsize {
z.buf = z.b[:]
} else {
z.buf = blist.get(bufsize)
}
}
z.buf = z.buf[:cap(z.buf)]
}
func (z *bufioEncWriter) flushErr() (err error) {
n, err := z.w.Write(z.buf[:z.n])
z.n -= n
if z.n > 0 {
if err == nil {
err = io.ErrShortWrite
}
if n > 0 {
copy(z.buf, z.buf[n:z.n+n])
}
}
return err
}
func (z *bufioEncWriter) flush() {
halt.onerror(z.flushErr())
}
func (z *bufioEncWriter) writeb(s []byte) {
LOOP:
a := len(z.buf) - z.n
if len(s) > a {
z.n += copy(z.buf[z.n:], s[:a])
s = s[a:]
z.flush()
goto LOOP
}
z.n += copy(z.buf[z.n:], s)
}
func (z *bufioEncWriter) writestr(s string) {
// z.writeb(bytesView(s)) // inlined below
LOOP:
a := len(z.buf) - z.n
if len(s) > a {
z.n += copy(z.buf[z.n:], s[:a])
s = s[a:]
z.flush()
goto LOOP
}
z.n += copy(z.buf[z.n:], s)
}
func (z *bufioEncWriter) writeqstr(s string) {
// z.writen1('"')
// z.writestr(s)
// z.writen1('"')
if z.n+len(s)+2 > len(z.buf) {
z.flush()
}
setByteAt(z.buf, uint(z.n), '"')
// z.buf[z.n] = '"'
z.n++
LOOP:
a := len(z.buf) - z.n
if len(s)+1 > a {
z.n += copy(z.buf[z.n:], s[:a])
s = s[a:]
z.flush()
goto LOOP
}
z.n += copy(z.buf[z.n:], s)
setByteAt(z.buf, uint(z.n), '"')
// z.buf[z.n] = '"'
z.n++
}
func (z *bufioEncWriter) writen1(b1 byte) {
if 1 > len(z.buf)-z.n {
z.flush()
}
setByteAt(z.buf, uint(z.n), b1)
// z.buf[z.n] = b1
z.n++
}
func (z *bufioEncWriter) writen2(b1, b2 byte) {
if 2 > len(z.buf)-z.n {
z.flush()
}
setByteAt(z.buf, uint(z.n+1), b2)
setByteAt(z.buf, uint(z.n), b1)
// z.buf[z.n+1] = b2
// z.buf[z.n] = b1
z.n += 2
}
func (z *bufioEncWriter) writen4(b [4]byte) {
if 4 > len(z.buf)-z.n {
z.flush()
}
// setByteAt(z.buf, uint(z.n+3), b4)
// setByteAt(z.buf, uint(z.n+2), b3)
// setByteAt(z.buf, uint(z.n+1), b2)
// setByteAt(z.buf, uint(z.n), b1)
copy(z.buf[z.n:], b[:])
z.n += 4
}
func (z *bufioEncWriter) writen8(b [8]byte) {
if 8 > len(z.buf)-z.n {
z.flush()
}
copy(z.buf[z.n:], b[:])
z.n += 8
}
func (z *bufioEncWriter) endErr() (err error) {
if z.n > 0 {
err = z.flushErr()
}
return
}
// ---------------------------------------------
// bytesEncAppender implements encWriter and can write to an byte slice.
type bytesEncAppender struct {
b []byte
out *[]byte
}
func (z *bytesEncAppender) writeb(s []byte) {
z.b = append(z.b, s...)
}
func (z *bytesEncAppender) writestr(s string) {
z.b = append(z.b, s...)
}
func (z *bytesEncAppender) writeqstr(s string) {
z.b = append(append(append(z.b, '"'), s...), '"')
// z.b = append(z.b, '"')
// z.b = append(z.b, s...)
// z.b = append(z.b, '"')
}
func (z *bytesEncAppender) writen1(b1 byte) {
z.b = append(z.b, b1)
}
func (z *bytesEncAppender) writen2(b1, b2 byte) {
z.b = append(z.b, b1, b2)
}
func (z *bytesEncAppender) writen4(b [4]byte) {
z.b = append(z.b, b[:]...)
// z.b = append(z.b, b1, b2, b3, b4) // prevents inlining encWr.writen4
}
func (z *bytesEncAppender) writen8(b [8]byte) {
z.b = append(z.b, b[:]...)
// z.b = append(z.b, b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]) // prevents inlining encWr.writen4
}
func (z *bytesEncAppender) endErr() error {
*(z.out) = z.b
return nil
}
func (z *bytesEncAppender) reset(in []byte, out *[]byte) {
z.b = in[:0]
z.out = out
}
// --------------------------------------------------
type encWr struct {
wb bytesEncAppender
wf *bufioEncWriter
bytes bool // encoding to []byte
// MARKER: these fields below should belong directly in Encoder.
// we pack them here for space efficiency and cache-line optimization.
js bool // is json encoder?
be bool // is binary encoder?
c containerState
calls uint16
seq uint16 // sequencer (e.g. used by binc for symbols, etc)
}
// MARKER: manually inline bytesEncAppender.writenx/writeqstr methods,
// as calling them causes encWr.writenx/writeqstr methods to not be inlined (cost > 80).
//
// i.e. e.g. instead of writing z.wb.writen2(b1, b2), use z.wb.b = append(z.wb.b, b1, b2)
func (z *encWr) writeb(s []byte) {
if z.bytes {
z.wb.writeb(s)
} else {
z.wf.writeb(s)
}
}
func (z *encWr) writestr(s string) {
if z.bytes {
z.wb.writestr(s)
} else {
z.wf.writestr(s)
}
}
// MARKER: Add WriteStr to be called directly by generated code without a genHelper forwarding function.
// Go's inlining model adds cost for forwarding functions, preventing inlining (cost goes above 80 budget).
func (z *encWr) WriteStr(s string) {
if z.bytes {
z.wb.writestr(s)
} else {
z.wf.writestr(s)
}
}
func (z *encWr) writen1(b1 byte) {
if z.bytes {
z.wb.writen1(b1)
} else {
z.wf.writen1(b1)
}
}
func (z *encWr) writen2(b1, b2 byte) {
if z.bytes {
// MARKER: z.wb.writen2(b1, b2)
z.wb.b = append(z.wb.b, b1, b2)
} else {
z.wf.writen2(b1, b2)
}
}
func (z *encWr) writen4(b [4]byte) {
if z.bytes {
// MARKER: z.wb.writen4(b1, b2, b3, b4)
z.wb.b = append(z.wb.b, b[:]...)
// z.wb.writen4(b)
} else {
z.wf.writen4(b)
}
}
func (z *encWr) writen8(b [8]byte) {
if z.bytes {
// z.wb.b = append(z.wb.b, b[:]...)
z.wb.writen8(b)
} else {
z.wf.writen8(b)
}
}
func (z *encWr) writeqstr(s string) {
if z.bytes {
// MARKER: z.wb.writeqstr(s)
z.wb.b = append(append(append(z.wb.b, '"'), s...), '"')
} else {
z.wf.writeqstr(s)
}
}
func (z *encWr) endErr() error {
if z.bytes {
return z.wb.endErr()
}
return z.wf.endErr()
}
func (z *encWr) end() {
halt.onerror(z.endErr())
}
var _ encWriter = (*encWr)(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/ugorji/go/codec/reader.go | vendor/github.com/ugorji/go/codec/reader.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
package codec
import (
"bufio"
"bytes"
"io"
"strings"
)
// decReader abstracts the reading source, allowing implementations that can
// read from an io.Reader or directly off a byte slice with zero-copying.
type decReader interface {
// readx will return a view of the []byte if decoding from a []byte, OR
// read into the implementation scratch buffer if possible i.e. n < len(scratchbuf), OR
// create a new []byte and read into that
readx(n uint) []byte
readb([]byte)
readn1() byte
readn2() [2]byte
readn3() [3]byte
readn4() [4]byte
readn8() [8]byte
// readn1eof() (v uint8, eof bool)
// // read up to 8 bytes at a time
// readn(num uint8) (v [8]byte)
numread() uint // number of bytes read
// skip any whitespace characters, and return the first non-matching byte
skipWhitespace() (token byte)
// jsonReadNum will include last read byte in first element of slice,
// and continue numeric characters until it sees a non-numeric char
// or EOF. If it sees a non-numeric character, it will unread that.
jsonReadNum() []byte
// jsonReadAsisChars will read json plain characters (anything but " or \)
// and return a slice terminated by a non-json asis character.
jsonReadAsisChars() []byte
// skip will skip any byte that matches, and return the first non-matching byte
// skip(accept *bitset256) (token byte)
// readTo will read any byte that matches, stopping once no-longer matching.
// readTo(accept *bitset256) (out []byte)
// readUntil will read, only stopping once it matches the 'stop' byte (which it excludes).
readUntil(stop byte) (out []byte)
}
// ------------------------------------------------
type unreadByteStatus uint8
// unreadByteStatus goes from
// undefined (when initialized) -- (read) --> canUnread -- (unread) --> canRead ...
const (
unreadByteUndefined unreadByteStatus = iota
unreadByteCanRead
unreadByteCanUnread
)
// const defBufReaderSize = 4096
// --------------------
// ioReaderByteScanner contains the io.Reader and io.ByteScanner interfaces
type ioReaderByteScanner interface {
io.Reader
io.ByteScanner
// ReadByte() (byte, error)
// UnreadByte() error
// Read(p []byte) (n int, err error)
}
// ioReaderByteScannerT does a simple wrapper of a io.ByteScanner
// over a io.Reader
type ioReaderByteScannerT struct {
r io.Reader
l byte // last byte
ls unreadByteStatus // last byte status
_ [2]byte // padding
b [4]byte // tiny buffer for reading single bytes
}
func (z *ioReaderByteScannerT) ReadByte() (c byte, err error) {
if z.ls == unreadByteCanRead {
z.ls = unreadByteCanUnread
c = z.l
} else {
_, err = z.Read(z.b[:1])
c = z.b[0]
}
return
}
func (z *ioReaderByteScannerT) UnreadByte() (err error) {
switch z.ls {
case unreadByteCanUnread:
z.ls = unreadByteCanRead
case unreadByteCanRead:
err = errDecUnreadByteLastByteNotRead
case unreadByteUndefined:
err = errDecUnreadByteNothingToRead
default:
err = errDecUnreadByteUnknown
}
return
}
func (z *ioReaderByteScannerT) Read(p []byte) (n int, err error) {
if len(p) == 0 {
return
}
var firstByte bool
if z.ls == unreadByteCanRead {
z.ls = unreadByteCanUnread
p[0] = z.l
if len(p) == 1 {
n = 1
return
}
firstByte = true
p = p[1:]
}
n, err = z.r.Read(p)
if n > 0 {
if err == io.EOF && n == len(p) {
err = nil // read was successful, so postpone EOF (till next time)
}
z.l = p[n-1]
z.ls = unreadByteCanUnread
}
if firstByte {
n++
}
return
}
func (z *ioReaderByteScannerT) reset(r io.Reader) {
z.r = r
z.ls = unreadByteUndefined
z.l = 0
}
// ioDecReader is a decReader that reads off an io.Reader.
type ioDecReader struct {
rr ioReaderByteScannerT // the reader passed in, wrapped into a reader+bytescanner
n uint // num read
blist *bytesFreelist
bufr []byte // buffer for readTo/readUntil
br ioReaderByteScanner // main reader used for Read|ReadByte|UnreadByte
bb *bufio.Reader // created internally, and reused on reset if needed
x [64 + 40]byte // for: get struct field name, swallow valueTypeBytes, etc
}
func (z *ioDecReader) reset(r io.Reader, bufsize int, blist *bytesFreelist) {
z.blist = blist
z.n = 0
z.bufr = z.blist.check(z.bufr, 256)
z.br = nil
var ok bool
if bufsize <= 0 {
z.br, ok = r.(ioReaderByteScanner)
if !ok {
z.rr.reset(r)
z.br = &z.rr
}
return
}
// bufsize > 0 ...
// if bytes.[Buffer|Reader], no value in adding extra buffer
// if bufio.Reader, no value in extra buffer unless size changes
switch bb := r.(type) {
case *strings.Reader:
z.br = bb
case *bytes.Buffer:
z.br = bb
case *bytes.Reader:
z.br = bb
case *bufio.Reader:
if bb.Size() == bufsize {
z.br = bb
}
}
if z.br == nil {
if z.bb != nil && z.bb.Size() == bufsize {
z.bb.Reset(r)
} else {
z.bb = bufio.NewReaderSize(r, bufsize)
}
z.br = z.bb
}
}
func (z *ioDecReader) numread() uint {
return z.n
}
func (z *ioDecReader) readn1() (b uint8) {
b, err := z.br.ReadByte()
halt.onerror(err)
z.n++
return
}
func (z *ioDecReader) readn2() (bs [2]byte) {
z.readb(bs[:])
return
}
func (z *ioDecReader) readn3() (bs [3]byte) {
z.readb(bs[:])
return
}
func (z *ioDecReader) readn4() (bs [4]byte) {
z.readb(bs[:])
return
}
func (z *ioDecReader) readn8() (bs [8]byte) {
z.readb(bs[:])
return
}
func (z *ioDecReader) readx(n uint) (bs []byte) {
if n == 0 {
return zeroByteSlice
}
if n < uint(len(z.x)) {
bs = z.x[:n]
} else {
bs = make([]byte, n)
}
nn, err := readFull(z.br, bs)
z.n += nn
halt.onerror(err)
return
}
func (z *ioDecReader) readb(bs []byte) {
if len(bs) == 0 {
return
}
nn, err := readFull(z.br, bs)
z.n += nn
halt.onerror(err)
}
// func (z *ioDecReader) readn1eof() (b uint8, eof bool) {
// b, err := z.br.ReadByte()
// if err == nil {
// z.n++
// } else if err == io.EOF {
// eof = true
// } else {
// halt.onerror(err)
// }
// return
// }
func (z *ioDecReader) jsonReadNum() (bs []byte) {
z.unreadn1()
z.bufr = z.bufr[:0]
LOOP:
// i, eof := z.readn1eof()
i, err := z.br.ReadByte()
if err == io.EOF {
return z.bufr
}
if err != nil {
halt.onerror(err)
}
z.n++
if isNumberChar(i) {
z.bufr = append(z.bufr, i)
goto LOOP
}
z.unreadn1()
return z.bufr
}
func (z *ioDecReader) jsonReadAsisChars() (bs []byte) {
z.bufr = z.bufr[:0]
LOOP:
i := z.readn1()
z.bufr = append(z.bufr, i)
if i == '"' || i == '\\' {
return z.bufr
}
goto LOOP
}
func (z *ioDecReader) skipWhitespace() (token byte) {
LOOP:
token = z.readn1()
if isWhitespaceChar(token) {
goto LOOP
}
return
}
// func (z *ioDecReader) readUntil(stop byte) []byte {
// z.bufr = z.bufr[:0]
// LOOP:
// token := z.readn1()
// z.bufr = append(z.bufr, token)
// if token == stop {
// return z.bufr[:len(z.bufr)-1]
// }
// goto LOOP
// }
func (z *ioDecReader) readUntil(stop byte) []byte {
z.bufr = z.bufr[:0]
LOOP:
token := z.readn1()
if token == stop {
return z.bufr
}
z.bufr = append(z.bufr, token)
goto LOOP
}
func (z *ioDecReader) unreadn1() {
err := z.br.UnreadByte()
halt.onerror(err)
z.n--
}
// ------------------------------------
// bytesDecReader is a decReader that reads off a byte slice with zero copying
//
// Note: we do not try to convert index'ing out of bounds to an io error.
// instead, we let it bubble up to the exported Encode/Decode method
// and recover it as an io error.
//
// Every function here MUST defensively check bounds either explicitly
// or via a bounds check.
//
// see panicValToErr(...) function in helper.go.
type bytesDecReader struct {
b []byte // data
c uint // cursor
}
func (z *bytesDecReader) reset(in []byte) {
z.b = in[:len(in):len(in)] // reslicing must not go past capacity
z.c = 0
}
func (z *bytesDecReader) numread() uint {
return z.c
}
// Note: slicing from a non-constant start position is more expensive,
// as more computation is required to decipher the pointer start position.
// However, we do it only once, and it's better than reslicing both z.b and return value.
func (z *bytesDecReader) readx(n uint) (bs []byte) {
// x := z.c + n
// bs = z.b[z.c:x]
// z.c = x
bs = z.b[z.c : z.c+n]
z.c += n
return
}
func (z *bytesDecReader) readb(bs []byte) {
copy(bs, z.readx(uint(len(bs))))
}
// MARKER: do not use this - as it calls into memmove (as the size of data to move is unknown)
// func (z *bytesDecReader) readnn(bs []byte, n uint) {
// x := z.c
// copy(bs, z.b[x:x+n])
// z.c += n
// }
// func (z *bytesDecReader) readn(num uint8) (bs [8]byte) {
// x := z.c + uint(num)
// copy(bs[:], z.b[z.c:x]) // slice z.b completely, so we get bounds error if past
// z.c = x
// return
// }
// func (z *bytesDecReader) readn1() uint8 {
// z.c++
// return z.b[z.c-1]
// }
// MARKER: readn{1,2,3,4,8} should throw an out of bounds error if past length.
// MARKER: readn1: explicitly ensure bounds check is done
// MARKER: readn{2,3,4,8}: ensure you slice z.b completely so we get bounds error if past end.
func (z *bytesDecReader) readn1() (v uint8) {
v = z.b[z.c]
z.c++
return
}
func (z *bytesDecReader) readn2() (bs [2]byte) {
// copy(bs[:], z.b[z.c:z.c+2])
// bs[1] = z.b[z.c+1]
// bs[0] = z.b[z.c]
bs = okBytes2(z.b[z.c : z.c+2])
z.c += 2
return
}
func (z *bytesDecReader) readn3() (bs [3]byte) {
// copy(bs[1:], z.b[z.c:z.c+3])
bs = okBytes3(z.b[z.c : z.c+3])
z.c += 3
return
}
func (z *bytesDecReader) readn4() (bs [4]byte) {
// copy(bs[:], z.b[z.c:z.c+4])
bs = okBytes4(z.b[z.c : z.c+4])
z.c += 4
return
}
func (z *bytesDecReader) readn8() (bs [8]byte) {
// copy(bs[:], z.b[z.c:z.c+8])
bs = okBytes8(z.b[z.c : z.c+8])
z.c += 8
return
}
func (z *bytesDecReader) jsonReadNum() []byte {
z.c-- // unread
i := z.c
LOOP:
// gracefully handle end of slice, as end of stream is meaningful here
if i < uint(len(z.b)) && isNumberChar(z.b[i]) {
i++
goto LOOP
}
z.c, i = i, z.c
// MARKER: 20230103: byteSliceOf here prevents inlining of jsonReadNum
// return byteSliceOf(z.b, i, z.c)
return z.b[i:z.c]
}
func (z *bytesDecReader) jsonReadAsisChars() []byte {
i := z.c
LOOP:
token := z.b[i]
i++
if token == '"' || token == '\\' {
z.c, i = i, z.c
return byteSliceOf(z.b, i, z.c)
// return z.b[i:z.c]
}
goto LOOP
}
func (z *bytesDecReader) skipWhitespace() (token byte) {
i := z.c
LOOP:
token = z.b[i]
if isWhitespaceChar(token) {
i++
goto LOOP
}
z.c = i + 1
return
}
func (z *bytesDecReader) readUntil(stop byte) (out []byte) {
i := z.c
LOOP:
if z.b[i] == stop {
out = byteSliceOf(z.b, z.c, i)
// out = z.b[z.c:i]
z.c = i + 1
return
}
i++
goto LOOP
}
// --------------
type decRd struct {
rb bytesDecReader
ri *ioDecReader
decReader
bytes bool // is bytes reader
// MARKER: these fields below should belong directly in Encoder.
// we pack them here for space efficiency and cache-line optimization.
mtr bool // is maptype a known type?
str bool // is slicetype a known type?
be bool // is binary encoding
js bool // is json handle
jsms bool // is json handle, and MapKeyAsString
cbor bool // is cbor handle
cbreak bool // is a check breaker
}
// From out benchmarking, we see the following impact performance:
//
// - functions that are too big to inline
// - interface calls (as no inlining can occur)
//
// decRd is designed to embed a decReader, and then re-implement some of the decReader
// methods using a conditional branch.
//
// We only override the ones where the bytes version is inlined AND the wrapper method
// (containing the bytes version alongside a conditional branch) is also inlined.
//
// We use ./run.sh -z to check.
//
// Right now, only numread and "carefully crafted" readn1 can be inlined.
func (z *decRd) numread() uint {
if z.bytes {
return z.rb.numread()
}
return z.ri.numread()
}
func (z *decRd) readn1() (v uint8) {
if z.bytes {
// return z.rb.readn1()
// MARKER: calling z.rb.readn1() prevents decRd.readn1 from being inlined.
// copy code, to manually inline and explicitly return here.
// Keep in sync with bytesDecReader.readn1
v = z.rb.b[z.rb.c]
z.rb.c++
return
}
return z.ri.readn1()
}
// func (z *decRd) readn4() [4]byte {
// if z.bytes {
// return z.rb.readn4()
// }
// return z.ri.readn4()
// }
// func (z *decRd) readn3() [3]byte {
// if z.bytes {
// return z.rb.readn3()
// }
// return z.ri.readn3()
// }
// func (z *decRd) skipWhitespace() byte {
// if z.bytes {
// return z.rb.skipWhitespace()
// }
// return z.ri.skipWhitespace()
// }
type devNullReader struct{}
func (devNullReader) Read(p []byte) (int, error) { return 0, io.EOF }
func (devNullReader) Close() error { return nil }
func readFull(r io.Reader, bs []byte) (n uint, err error) {
var nn int
for n < uint(len(bs)) && err == nil {
nn, err = r.Read(bs[n:])
if nn > 0 {
if err == io.EOF {
// leave EOF for next time
err = nil
}
n += uint(nn)
}
}
// do not do this below - it serves no purpose
// if n != len(bs) && err == io.EOF { err = io.ErrUnexpectedEOF }
return
}
var _ decReader = (*decRd)(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/ugorji/go/codec/binc.go | vendor/github.com/ugorji/go/codec/binc.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
package codec
import (
"math"
"reflect"
"time"
"unicode/utf8"
)
// Symbol management:
// - symbols are stored in a symbol map during encoding and decoding.
// - the symbols persist until the (En|De)coder ResetXXX method is called.
const bincDoPrune = true
// vd as low 4 bits (there are 16 slots)
const (
bincVdSpecial byte = iota
bincVdPosInt
bincVdNegInt
bincVdFloat
bincVdString
bincVdByteArray
bincVdArray
bincVdMap
bincVdTimestamp
bincVdSmallInt
_ // bincVdUnicodeOther
bincVdSymbol
_ // bincVdDecimal
_ // open slot
_ // open slot
bincVdCustomExt = 0x0f
)
const (
bincSpNil byte = iota
bincSpFalse
bincSpTrue
bincSpNan
bincSpPosInf
bincSpNegInf
bincSpZeroFloat
bincSpZero
bincSpNegOne
)
const (
_ byte = iota // bincFlBin16
bincFlBin32
_ // bincFlBin32e
bincFlBin64
_ // bincFlBin64e
// others not currently supported
)
const bincBdNil = 0 // bincVdSpecial<<4 | bincSpNil // staticcheck barfs on this (SA4016)
var (
bincdescSpecialVsNames = map[byte]string{
bincSpNil: "nil",
bincSpFalse: "false",
bincSpTrue: "true",
bincSpNan: "float",
bincSpPosInf: "float",
bincSpNegInf: "float",
bincSpZeroFloat: "float",
bincSpZero: "uint",
bincSpNegOne: "int",
}
bincdescVdNames = map[byte]string{
bincVdSpecial: "special",
bincVdSmallInt: "uint",
bincVdPosInt: "uint",
bincVdFloat: "float",
bincVdSymbol: "string",
bincVdString: "string",
bincVdByteArray: "bytes",
bincVdTimestamp: "time",
bincVdCustomExt: "ext",
bincVdArray: "array",
bincVdMap: "map",
}
)
func bincdescbd(bd byte) (s string) {
return bincdesc(bd>>4, bd&0x0f)
}
func bincdesc(vd, vs byte) (s string) {
if vd == bincVdSpecial {
s = bincdescSpecialVsNames[vs]
} else {
s = bincdescVdNames[vd]
}
if s == "" {
s = "unknown"
}
return
}
type bincEncState struct {
m map[string]uint16 // symbols
}
func (e bincEncState) captureState() interface{} { return e.m }
func (e *bincEncState) resetState() { e.m = nil }
func (e *bincEncState) reset() { e.resetState() }
func (e *bincEncState) restoreState(v interface{}) { e.m = v.(map[string]uint16) }
type bincEncDriver struct {
noBuiltInTypes
encDriverNoopContainerWriter
h *BincHandle
bincEncState
e Encoder
}
func (e *bincEncDriver) encoder() *Encoder {
return &e.e
}
func (e *bincEncDriver) EncodeNil() {
e.e.encWr.writen1(bincBdNil)
}
func (e *bincEncDriver) EncodeTime(t time.Time) {
if t.IsZero() {
e.EncodeNil()
} else {
bs := bincEncodeTime(t)
e.e.encWr.writen1(bincVdTimestamp<<4 | uint8(len(bs)))
e.e.encWr.writeb(bs)
}
}
func (e *bincEncDriver) EncodeBool(b bool) {
if b {
e.e.encWr.writen1(bincVdSpecial<<4 | bincSpTrue)
} else {
e.e.encWr.writen1(bincVdSpecial<<4 | bincSpFalse)
}
}
func (e *bincEncDriver) encSpFloat(f float64) (done bool) {
if f == 0 {
e.e.encWr.writen1(bincVdSpecial<<4 | bincSpZeroFloat)
} else if math.IsNaN(float64(f)) {
e.e.encWr.writen1(bincVdSpecial<<4 | bincSpNan)
} else if math.IsInf(float64(f), +1) {
e.e.encWr.writen1(bincVdSpecial<<4 | bincSpPosInf)
} else if math.IsInf(float64(f), -1) {
e.e.encWr.writen1(bincVdSpecial<<4 | bincSpNegInf)
} else {
return
}
return true
}
func (e *bincEncDriver) EncodeFloat32(f float32) {
if !e.encSpFloat(float64(f)) {
e.e.encWr.writen1(bincVdFloat<<4 | bincFlBin32)
bigen.writeUint32(e.e.w(), math.Float32bits(f))
}
}
func (e *bincEncDriver) EncodeFloat64(f float64) {
if e.encSpFloat(f) {
return
}
b := bigen.PutUint64(math.Float64bits(f))
if bincDoPrune {
i := 7
for ; i >= 0 && (b[i] == 0); i-- {
}
i++
if i <= 6 {
e.e.encWr.writen1(bincVdFloat<<4 | 0x8 | bincFlBin64)
e.e.encWr.writen1(byte(i))
e.e.encWr.writeb(b[:i])
return
}
}
e.e.encWr.writen1(bincVdFloat<<4 | bincFlBin64)
e.e.encWr.writen8(b)
}
func (e *bincEncDriver) encIntegerPrune32(bd byte, pos bool, v uint64) {
b := bigen.PutUint32(uint32(v))
if bincDoPrune {
i := byte(pruneSignExt(b[:], pos))
e.e.encWr.writen1(bd | 3 - i)
e.e.encWr.writeb(b[i:])
} else {
e.e.encWr.writen1(bd | 3)
e.e.encWr.writen4(b)
}
}
func (e *bincEncDriver) encIntegerPrune64(bd byte, pos bool, v uint64) {
b := bigen.PutUint64(v)
if bincDoPrune {
i := byte(pruneSignExt(b[:], pos))
e.e.encWr.writen1(bd | 7 - i)
e.e.encWr.writeb(b[i:])
} else {
e.e.encWr.writen1(bd | 7)
e.e.encWr.writen8(b)
}
}
func (e *bincEncDriver) EncodeInt(v int64) {
if v >= 0 {
e.encUint(bincVdPosInt<<4, true, uint64(v))
} else if v == -1 {
e.e.encWr.writen1(bincVdSpecial<<4 | bincSpNegOne)
} else {
e.encUint(bincVdNegInt<<4, false, uint64(-v))
}
}
func (e *bincEncDriver) EncodeUint(v uint64) {
e.encUint(bincVdPosInt<<4, true, v)
}
func (e *bincEncDriver) encUint(bd byte, pos bool, v uint64) {
if v == 0 {
e.e.encWr.writen1(bincVdSpecial<<4 | bincSpZero)
} else if pos && v >= 1 && v <= 16 {
e.e.encWr.writen1(bincVdSmallInt<<4 | byte(v-1))
} else if v <= math.MaxUint8 {
e.e.encWr.writen2(bd|0x0, byte(v))
} else if v <= math.MaxUint16 {
e.e.encWr.writen1(bd | 0x01)
bigen.writeUint16(e.e.w(), uint16(v))
} else if v <= math.MaxUint32 {
e.encIntegerPrune32(bd, pos, v)
} else {
e.encIntegerPrune64(bd, pos, v)
}
}
func (e *bincEncDriver) EncodeExt(v interface{}, basetype reflect.Type, xtag uint64, ext Ext) {
var bs0, bs []byte
if ext == SelfExt {
bs0 = e.e.blist.get(1024)
bs = bs0
e.e.sideEncode(v, basetype, &bs)
} else {
bs = ext.WriteExt(v)
}
if bs == nil {
e.EncodeNil()
goto END
}
e.encodeExtPreamble(uint8(xtag), len(bs))
e.e.encWr.writeb(bs)
END:
if ext == SelfExt {
e.e.blist.put(bs)
if !byteSliceSameData(bs0, bs) {
e.e.blist.put(bs0)
}
}
}
func (e *bincEncDriver) EncodeRawExt(re *RawExt) {
e.encodeExtPreamble(uint8(re.Tag), len(re.Data))
e.e.encWr.writeb(re.Data)
}
func (e *bincEncDriver) encodeExtPreamble(xtag byte, length int) {
e.encLen(bincVdCustomExt<<4, uint64(length))
e.e.encWr.writen1(xtag)
}
func (e *bincEncDriver) WriteArrayStart(length int) {
e.encLen(bincVdArray<<4, uint64(length))
}
func (e *bincEncDriver) WriteMapStart(length int) {
e.encLen(bincVdMap<<4, uint64(length))
}
func (e *bincEncDriver) EncodeSymbol(v string) {
//symbols only offer benefit when string length > 1.
//This is because strings with length 1 take only 2 bytes to store
//(bd with embedded length, and single byte for string val).
l := len(v)
if l == 0 {
e.encBytesLen(cUTF8, 0)
return
} else if l == 1 {
e.encBytesLen(cUTF8, 1)
e.e.encWr.writen1(v[0])
return
}
if e.m == nil {
e.m = make(map[string]uint16, 16)
}
ui, ok := e.m[v]
if ok {
if ui <= math.MaxUint8 {
e.e.encWr.writen2(bincVdSymbol<<4, byte(ui))
} else {
e.e.encWr.writen1(bincVdSymbol<<4 | 0x8)
bigen.writeUint16(e.e.w(), ui)
}
} else {
e.e.seq++
ui = e.e.seq
e.m[v] = ui
var lenprec uint8
if l <= math.MaxUint8 {
// lenprec = 0
} else if l <= math.MaxUint16 {
lenprec = 1
} else if int64(l) <= math.MaxUint32 {
lenprec = 2
} else {
lenprec = 3
}
if ui <= math.MaxUint8 {
e.e.encWr.writen2(bincVdSymbol<<4|0x0|0x4|lenprec, byte(ui))
} else {
e.e.encWr.writen1(bincVdSymbol<<4 | 0x8 | 0x4 | lenprec)
bigen.writeUint16(e.e.w(), ui)
}
if lenprec == 0 {
e.e.encWr.writen1(byte(l))
} else if lenprec == 1 {
bigen.writeUint16(e.e.w(), uint16(l))
} else if lenprec == 2 {
bigen.writeUint32(e.e.w(), uint32(l))
} else {
bigen.writeUint64(e.e.w(), uint64(l))
}
e.e.encWr.writestr(v)
}
}
func (e *bincEncDriver) EncodeString(v string) {
if e.h.StringToRaw {
e.encLen(bincVdByteArray<<4, uint64(len(v)))
if len(v) > 0 {
e.e.encWr.writestr(v)
}
return
}
e.EncodeStringEnc(cUTF8, v)
}
func (e *bincEncDriver) EncodeStringEnc(c charEncoding, v string) {
if e.e.c == containerMapKey && c == cUTF8 && (e.h.AsSymbols == 1) {
e.EncodeSymbol(v)
return
}
e.encLen(bincVdString<<4, uint64(len(v)))
if len(v) > 0 {
e.e.encWr.writestr(v)
}
}
func (e *bincEncDriver) EncodeStringBytesRaw(v []byte) {
if v == nil {
e.EncodeNil()
return
}
e.encLen(bincVdByteArray<<4, uint64(len(v)))
if len(v) > 0 {
e.e.encWr.writeb(v)
}
}
func (e *bincEncDriver) encBytesLen(c charEncoding, length uint64) {
// MARKER: we currently only support UTF-8 (string) and RAW (bytearray).
// We should consider supporting bincUnicodeOther.
if c == cRAW {
e.encLen(bincVdByteArray<<4, length)
} else {
e.encLen(bincVdString<<4, length)
}
}
func (e *bincEncDriver) encLen(bd byte, l uint64) {
if l < 12 {
e.e.encWr.writen1(bd | uint8(l+4))
} else {
e.encLenNumber(bd, l)
}
}
func (e *bincEncDriver) encLenNumber(bd byte, v uint64) {
if v <= math.MaxUint8 {
e.e.encWr.writen2(bd, byte(v))
} else if v <= math.MaxUint16 {
e.e.encWr.writen1(bd | 0x01)
bigen.writeUint16(e.e.w(), uint16(v))
} else if v <= math.MaxUint32 {
e.e.encWr.writen1(bd | 0x02)
bigen.writeUint32(e.e.w(), uint32(v))
} else {
e.e.encWr.writen1(bd | 0x03)
bigen.writeUint64(e.e.w(), uint64(v))
}
}
//------------------------------------
type bincDecState struct {
bdRead bool
bd byte
vd byte
vs byte
_ bool
// MARKER: consider using binary search here instead of a map (ie bincDecSymbol)
s map[uint16][]byte
}
func (x bincDecState) captureState() interface{} { return x }
func (x *bincDecState) resetState() { *x = bincDecState{} }
func (x *bincDecState) reset() { x.resetState() }
func (x *bincDecState) restoreState(v interface{}) { *x = v.(bincDecState) }
type bincDecDriver struct {
decDriverNoopContainerReader
decDriverNoopNumberHelper
noBuiltInTypes
h *BincHandle
bincDecState
d Decoder
}
func (d *bincDecDriver) decoder() *Decoder {
return &d.d
}
func (d *bincDecDriver) descBd() string {
return sprintf("%v (%s)", d.bd, bincdescbd(d.bd))
}
func (d *bincDecDriver) readNextBd() {
d.bd = d.d.decRd.readn1()
d.vd = d.bd >> 4
d.vs = d.bd & 0x0f
d.bdRead = true
}
func (d *bincDecDriver) advanceNil() (null bool) {
if !d.bdRead {
d.readNextBd()
}
if d.bd == bincBdNil {
d.bdRead = false
return true // null = true
}
return
}
func (d *bincDecDriver) TryNil() bool {
return d.advanceNil()
}
func (d *bincDecDriver) ContainerType() (vt valueType) {
if !d.bdRead {
d.readNextBd()
}
if d.bd == bincBdNil {
d.bdRead = false
return valueTypeNil
} else if d.vd == bincVdByteArray {
return valueTypeBytes
} else if d.vd == bincVdString {
return valueTypeString
} else if d.vd == bincVdArray {
return valueTypeArray
} else if d.vd == bincVdMap {
return valueTypeMap
}
return valueTypeUnset
}
func (d *bincDecDriver) DecodeTime() (t time.Time) {
if d.advanceNil() {
return
}
if d.vd != bincVdTimestamp {
d.d.errorf("cannot decode time - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
}
t, err := bincDecodeTime(d.d.decRd.readx(uint(d.vs)))
halt.onerror(err)
d.bdRead = false
return
}
func (d *bincDecDriver) decFloatPruned(maxlen uint8) {
l := d.d.decRd.readn1()
if l > maxlen {
d.d.errorf("cannot read float - at most %v bytes used to represent float - received %v bytes", maxlen, l)
}
for i := l; i < maxlen; i++ {
d.d.b[i] = 0
}
d.d.decRd.readb(d.d.b[0:l])
}
func (d *bincDecDriver) decFloatPre32() (b [4]byte) {
if d.vs&0x8 == 0 {
b = d.d.decRd.readn4()
} else {
d.decFloatPruned(4)
copy(b[:], d.d.b[:])
}
return
}
func (d *bincDecDriver) decFloatPre64() (b [8]byte) {
if d.vs&0x8 == 0 {
b = d.d.decRd.readn8()
} else {
d.decFloatPruned(8)
copy(b[:], d.d.b[:])
}
return
}
func (d *bincDecDriver) decFloatVal() (f float64) {
switch d.vs & 0x7 {
case bincFlBin32:
f = float64(math.Float32frombits(bigen.Uint32(d.decFloatPre32())))
case bincFlBin64:
f = math.Float64frombits(bigen.Uint64(d.decFloatPre64()))
default:
// ok = false
d.d.errorf("read float supports only float32/64 - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
}
return
}
func (d *bincDecDriver) decUint() (v uint64) {
switch d.vs {
case 0:
v = uint64(d.d.decRd.readn1())
case 1:
v = uint64(bigen.Uint16(d.d.decRd.readn2()))
case 2:
b3 := d.d.decRd.readn3()
var b [4]byte
copy(b[1:], b3[:])
v = uint64(bigen.Uint32(b))
case 3:
v = uint64(bigen.Uint32(d.d.decRd.readn4()))
case 4, 5, 6:
var b [8]byte
lim := 7 - d.vs
bs := d.d.b[lim:8]
d.d.decRd.readb(bs)
copy(b[lim:], bs)
v = bigen.Uint64(b)
case 7:
v = bigen.Uint64(d.d.decRd.readn8())
default:
d.d.errorf("unsigned integers with greater than 64 bits of precision not supported: d.vs: %v %x", d.vs, d.vs)
}
return
}
func (d *bincDecDriver) uintBytes() (bs []byte) {
switch d.vs {
case 0:
bs = d.d.b[:1]
bs[0] = d.d.decRd.readn1()
case 1:
bs = d.d.b[:2]
d.d.decRd.readb(bs)
case 2:
bs = d.d.b[:3]
d.d.decRd.readb(bs)
case 3:
bs = d.d.b[:4]
d.d.decRd.readb(bs)
case 4, 5, 6:
lim := 7 - d.vs
bs = d.d.b[lim:8]
d.d.decRd.readb(bs)
case 7:
bs = d.d.b[:8]
d.d.decRd.readb(bs)
default:
d.d.errorf("unsigned integers with greater than 64 bits of precision not supported: d.vs: %v %x", d.vs, d.vs)
}
return
}
func (d *bincDecDriver) decInteger() (ui uint64, neg, ok bool) {
ok = true
vd, vs := d.vd, d.vs
if vd == bincVdPosInt {
ui = d.decUint()
} else if vd == bincVdNegInt {
ui = d.decUint()
neg = true
} else if vd == bincVdSmallInt {
ui = uint64(d.vs) + 1
} else if vd == bincVdSpecial {
if vs == bincSpZero {
// i = 0
} else if vs == bincSpNegOne {
neg = true
ui = 1
} else {
ok = false
// d.d.errorf("integer decode has invalid special value %x-%x/%s", d.vd, d.vs, bincdesc(d.vd, d.vs))
}
} else {
ok = false
// d.d.errorf("integer can only be decoded from int/uint. d.bd: 0x%x, d.vd: 0x%x", d.bd, d.vd)
}
return
}
func (d *bincDecDriver) decFloat() (f float64, ok bool) {
ok = true
vd, vs := d.vd, d.vs
if vd == bincVdSpecial {
if vs == bincSpNan {
f = math.NaN()
} else if vs == bincSpPosInf {
f = math.Inf(1)
} else if vs == bincSpZeroFloat || vs == bincSpZero {
} else if vs == bincSpNegInf {
f = math.Inf(-1)
} else {
ok = false
// d.d.errorf("float - invalid special value %x-%x/%s", d.vd, d.vs, bincdesc(d.vd, d.vs))
}
} else if vd == bincVdFloat {
f = d.decFloatVal()
} else {
ok = false
}
return
}
func (d *bincDecDriver) DecodeInt64() (i int64) {
if d.advanceNil() {
return
}
i = decNegintPosintFloatNumberHelper{&d.d}.int64(d.decInteger())
d.bdRead = false
return
}
func (d *bincDecDriver) DecodeUint64() (ui uint64) {
if d.advanceNil() {
return
}
ui = decNegintPosintFloatNumberHelper{&d.d}.uint64(d.decInteger())
d.bdRead = false
return
}
func (d *bincDecDriver) DecodeFloat64() (f float64) {
if d.advanceNil() {
return
}
f = decNegintPosintFloatNumberHelper{&d.d}.float64(d.decFloat())
d.bdRead = false
return
}
func (d *bincDecDriver) DecodeBool() (b bool) {
if d.advanceNil() {
return
}
if d.bd == (bincVdSpecial | bincSpFalse) {
// b = false
} else if d.bd == (bincVdSpecial | bincSpTrue) {
b = true
} else {
d.d.errorf("bool - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
}
d.bdRead = false
return
}
func (d *bincDecDriver) ReadMapStart() (length int) {
if d.advanceNil() {
return containerLenNil
}
if d.vd != bincVdMap {
d.d.errorf("map - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
}
length = d.decLen()
d.bdRead = false
return
}
func (d *bincDecDriver) ReadArrayStart() (length int) {
if d.advanceNil() {
return containerLenNil
}
if d.vd != bincVdArray {
d.d.errorf("array - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
}
length = d.decLen()
d.bdRead = false
return
}
func (d *bincDecDriver) decLen() int {
if d.vs > 3 {
return int(d.vs - 4)
}
return int(d.decLenNumber())
}
func (d *bincDecDriver) decLenNumber() (v uint64) {
if x := d.vs; x == 0 {
v = uint64(d.d.decRd.readn1())
} else if x == 1 {
v = uint64(bigen.Uint16(d.d.decRd.readn2()))
} else if x == 2 {
v = uint64(bigen.Uint32(d.d.decRd.readn4()))
} else {
v = bigen.Uint64(d.d.decRd.readn8())
}
return
}
// func (d *bincDecDriver) decStringBytes(bs []byte, zerocopy bool) (bs2 []byte) {
func (d *bincDecDriver) DecodeStringAsBytes() (bs2 []byte) {
d.d.decByteState = decByteStateNone
if d.advanceNil() {
return
}
var slen = -1
switch d.vd {
case bincVdString, bincVdByteArray:
slen = d.decLen()
if d.d.bytes {
d.d.decByteState = decByteStateZerocopy
bs2 = d.d.decRd.rb.readx(uint(slen))
} else {
d.d.decByteState = decByteStateReuseBuf
bs2 = decByteSlice(d.d.r(), slen, d.d.h.MaxInitLen, d.d.b[:])
}
case bincVdSymbol:
// zerocopy doesn't apply for symbols,
// as the values must be stored in a table for later use.
var symbol uint16
vs := d.vs
if vs&0x8 == 0 {
symbol = uint16(d.d.decRd.readn1())
} else {
symbol = uint16(bigen.Uint16(d.d.decRd.readn2()))
}
if d.s == nil {
d.s = make(map[uint16][]byte, 16)
}
if vs&0x4 == 0 {
bs2 = d.s[symbol]
} else {
switch vs & 0x3 {
case 0:
slen = int(d.d.decRd.readn1())
case 1:
slen = int(bigen.Uint16(d.d.decRd.readn2()))
case 2:
slen = int(bigen.Uint32(d.d.decRd.readn4()))
case 3:
slen = int(bigen.Uint64(d.d.decRd.readn8()))
}
// As we are using symbols, do not store any part of
// the parameter bs in the map, as it might be a shared buffer.
bs2 = decByteSlice(d.d.r(), slen, d.d.h.MaxInitLen, nil)
d.s[symbol] = bs2
}
default:
d.d.errorf("string/bytes - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
}
if d.h.ValidateUnicode && !utf8.Valid(bs2) {
d.d.errorf("DecodeStringAsBytes: invalid UTF-8: %s", bs2)
}
d.bdRead = false
return
}
func (d *bincDecDriver) DecodeBytes(bs []byte) (bsOut []byte) {
d.d.decByteState = decByteStateNone
if d.advanceNil() {
return
}
if d.vd == bincVdArray {
if bs == nil {
bs = d.d.b[:]
d.d.decByteState = decByteStateReuseBuf
}
slen := d.ReadArrayStart()
var changed bool
if bs, changed = usableByteSlice(bs, slen); changed {
d.d.decByteState = decByteStateNone
}
for i := 0; i < slen; i++ {
bs[i] = uint8(chkOvf.UintV(d.DecodeUint64(), 8))
}
for i := len(bs); i < slen; i++ {
bs = append(bs, uint8(chkOvf.UintV(d.DecodeUint64(), 8)))
}
return bs
}
var clen int
if d.vd == bincVdString || d.vd == bincVdByteArray {
clen = d.decLen()
} else {
d.d.errorf("bytes - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
}
d.bdRead = false
if d.d.zerocopy() {
d.d.decByteState = decByteStateZerocopy
return d.d.decRd.rb.readx(uint(clen))
}
if bs == nil {
bs = d.d.b[:]
d.d.decByteState = decByteStateReuseBuf
}
return decByteSlice(d.d.r(), clen, d.d.h.MaxInitLen, bs)
}
func (d *bincDecDriver) DecodeExt(rv interface{}, basetype reflect.Type, xtag uint64, ext Ext) {
if xtag > 0xff {
d.d.errorf("ext: tag must be <= 0xff; got: %v", xtag)
}
if d.advanceNil() {
return
}
xbs, realxtag1, zerocopy := d.decodeExtV(ext != nil, uint8(xtag))
realxtag := uint64(realxtag1)
if ext == nil {
re := rv.(*RawExt)
re.Tag = realxtag
re.setData(xbs, zerocopy)
} else if ext == SelfExt {
d.d.sideDecode(rv, basetype, xbs)
} else {
ext.ReadExt(rv, xbs)
}
}
func (d *bincDecDriver) decodeExtV(verifyTag bool, tag byte) (xbs []byte, xtag byte, zerocopy bool) {
if d.vd == bincVdCustomExt {
l := d.decLen()
xtag = d.d.decRd.readn1()
if verifyTag && xtag != tag {
d.d.errorf("wrong extension tag - got %b, expecting: %v", xtag, tag)
}
if d.d.bytes {
xbs = d.d.decRd.rb.readx(uint(l))
zerocopy = true
} else {
xbs = decByteSlice(d.d.r(), l, d.d.h.MaxInitLen, d.d.b[:])
}
} else if d.vd == bincVdByteArray {
xbs = d.DecodeBytes(nil)
} else {
d.d.errorf("ext expects extensions or byte array - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
}
d.bdRead = false
return
}
func (d *bincDecDriver) DecodeNaked() {
if !d.bdRead {
d.readNextBd()
}
n := d.d.naked()
var decodeFurther bool
switch d.vd {
case bincVdSpecial:
switch d.vs {
case bincSpNil:
n.v = valueTypeNil
case bincSpFalse:
n.v = valueTypeBool
n.b = false
case bincSpTrue:
n.v = valueTypeBool
n.b = true
case bincSpNan:
n.v = valueTypeFloat
n.f = math.NaN()
case bincSpPosInf:
n.v = valueTypeFloat
n.f = math.Inf(1)
case bincSpNegInf:
n.v = valueTypeFloat
n.f = math.Inf(-1)
case bincSpZeroFloat:
n.v = valueTypeFloat
n.f = float64(0)
case bincSpZero:
n.v = valueTypeUint
n.u = uint64(0) // int8(0)
case bincSpNegOne:
n.v = valueTypeInt
n.i = int64(-1) // int8(-1)
default:
d.d.errorf("cannot infer value - unrecognized special value %x-%x/%s", d.vd, d.vs, bincdesc(d.vd, d.vs))
}
case bincVdSmallInt:
n.v = valueTypeUint
n.u = uint64(int8(d.vs)) + 1 // int8(d.vs) + 1
case bincVdPosInt:
n.v = valueTypeUint
n.u = d.decUint()
case bincVdNegInt:
n.v = valueTypeInt
n.i = -(int64(d.decUint()))
case bincVdFloat:
n.v = valueTypeFloat
n.f = d.decFloatVal()
case bincVdString:
n.v = valueTypeString
n.s = d.d.stringZC(d.DecodeStringAsBytes())
case bincVdByteArray:
d.d.fauxUnionReadRawBytes(false)
case bincVdSymbol:
n.v = valueTypeSymbol
n.s = d.d.stringZC(d.DecodeStringAsBytes())
case bincVdTimestamp:
n.v = valueTypeTime
tt, err := bincDecodeTime(d.d.decRd.readx(uint(d.vs)))
halt.onerror(err)
n.t = tt
case bincVdCustomExt:
n.v = valueTypeExt
l := d.decLen()
n.u = uint64(d.d.decRd.readn1())
if d.d.bytes {
n.l = d.d.decRd.rb.readx(uint(l))
} else {
n.l = decByteSlice(d.d.r(), l, d.d.h.MaxInitLen, d.d.b[:])
}
case bincVdArray:
n.v = valueTypeArray
decodeFurther = true
case bincVdMap:
n.v = valueTypeMap
decodeFurther = true
default:
d.d.errorf("cannot infer value - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
}
if !decodeFurther {
d.bdRead = false
}
if n.v == valueTypeUint && d.h.SignedInteger {
n.v = valueTypeInt
n.i = int64(n.u)
}
}
func (d *bincDecDriver) nextValueBytes(v0 []byte) (v []byte) {
if !d.bdRead {
d.readNextBd()
}
v = v0
var h = decNextValueBytesHelper{d: &d.d}
var cursor = d.d.rb.c - 1
h.append1(&v, d.bd)
v = d.nextValueBytesBdReadR(v)
d.bdRead = false
h.bytesRdV(&v, cursor)
return
}
func (d *bincDecDriver) nextValueBytesR(v0 []byte) (v []byte) {
d.readNextBd()
v = v0
var h = decNextValueBytesHelper{d: &d.d}
h.append1(&v, d.bd)
return d.nextValueBytesBdReadR(v)
}
func (d *bincDecDriver) nextValueBytesBdReadR(v0 []byte) (v []byte) {
v = v0
var h = decNextValueBytesHelper{d: &d.d}
fnLen := func(vs byte) uint {
switch vs {
case 0:
x := d.d.decRd.readn1()
h.append1(&v, x)
return uint(x)
case 1:
x := d.d.decRd.readn2()
h.appendN(&v, x[:]...)
return uint(bigen.Uint16(x))
case 2:
x := d.d.decRd.readn4()
h.appendN(&v, x[:]...)
return uint(bigen.Uint32(x))
case 3:
x := d.d.decRd.readn8()
h.appendN(&v, x[:]...)
return uint(bigen.Uint64(x))
default:
return uint(vs - 4)
}
}
var clen uint
switch d.vd {
case bincVdSpecial:
switch d.vs {
case bincSpNil, bincSpFalse, bincSpTrue, bincSpNan, bincSpPosInf: // pass
case bincSpNegInf, bincSpZeroFloat, bincSpZero, bincSpNegOne: // pass
default:
d.d.errorf("cannot infer value - unrecognized special value %x-%x/%s", d.vd, d.vs, bincdesc(d.vd, d.vs))
}
case bincVdSmallInt: // pass
case bincVdPosInt, bincVdNegInt:
bs := d.uintBytes()
h.appendN(&v, bs...)
case bincVdFloat:
fn := func(xlen byte) {
if d.vs&0x8 != 0 {
xlen = d.d.decRd.readn1()
h.append1(&v, xlen)
if xlen > 8 {
d.d.errorf("cannot read float - at most 8 bytes used to represent float - received %v bytes", xlen)
}
}
d.d.decRd.readb(d.d.b[:xlen])
h.appendN(&v, d.d.b[:xlen]...)
}
switch d.vs & 0x7 {
case bincFlBin32:
fn(4)
case bincFlBin64:
fn(8)
default:
d.d.errorf("read float supports only float32/64 - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
}
case bincVdString, bincVdByteArray:
clen = fnLen(d.vs)
h.appendN(&v, d.d.decRd.readx(clen)...)
case bincVdSymbol:
if d.vs&0x8 == 0 {
h.append1(&v, d.d.decRd.readn1())
} else {
h.appendN(&v, d.d.decRd.rb.readx(2)...)
}
if d.vs&0x4 != 0 {
clen = fnLen(d.vs & 0x3)
h.appendN(&v, d.d.decRd.readx(clen)...)
}
case bincVdTimestamp:
h.appendN(&v, d.d.decRd.readx(uint(d.vs))...)
case bincVdCustomExt:
clen = fnLen(d.vs)
h.append1(&v, d.d.decRd.readn1()) // tag
h.appendN(&v, d.d.decRd.readx(clen)...)
case bincVdArray:
clen = fnLen(d.vs)
for i := uint(0); i < clen; i++ {
v = d.nextValueBytesR(v)
}
case bincVdMap:
clen = fnLen(d.vs)
for i := uint(0); i < clen; i++ {
v = d.nextValueBytesR(v)
v = d.nextValueBytesR(v)
}
default:
d.d.errorf("cannot infer value - %s %x-%x/%s", msgBadDesc, d.vd, d.vs, bincdesc(d.vd, d.vs))
}
return
}
//------------------------------------
// BincHandle is a Handle for the Binc Schema-Free Encoding Format
// defined at https://github.com/ugorji/binc .
//
// BincHandle currently supports all Binc features with the following EXCEPTIONS:
// - only integers up to 64 bits of precision are supported.
// big integers are unsupported.
// - Only IEEE 754 binary32 and binary64 floats are supported (ie Go float32 and float64 types).
// extended precision and decimal IEEE 754 floats are unsupported.
// - Only UTF-8 strings supported.
// Unicode_Other Binc types (UTF16, UTF32) are currently unsupported.
//
// Note that these EXCEPTIONS are temporary and full support is possible and may happen soon.
type BincHandle struct {
BasicHandle
binaryEncodingType
// noElemSeparators
// AsSymbols defines what should be encoded as symbols.
//
// Encoding as symbols can reduce the encoded size significantly.
//
// However, during decoding, each string to be encoded as a symbol must
// be checked to see if it has been seen before. Consequently, encoding time
// will increase if using symbols, because string comparisons has a clear cost.
//
// Values:
// - 0: default: library uses best judgement
// - 1: use symbols
// - 2: do not use symbols
AsSymbols uint8
// AsSymbols: may later on introduce more options ...
// - m: map keys
// - s: struct fields
// - n: none
// - a: all: same as m, s, ...
// _ [7]uint64 // padding (cache-aligned)
}
// Name returns the name of the handle: binc
func (h *BincHandle) Name() string { return "binc" }
func (h *BincHandle) desc(bd byte) string { return bincdesc(bd>>4, bd&0x0f) }
func (h *BincHandle) newEncDriver() encDriver {
var e = &bincEncDriver{h: h}
e.e.e = e
e.e.init(h)
e.reset()
return e
}
func (h *BincHandle) newDecDriver() decDriver {
d := &bincDecDriver{h: h}
d.d.d = d
d.d.init(h)
d.reset()
return d
}
// var timeDigits = [...]byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
// EncodeTime encodes a time.Time as a []byte, including
// information on the instant in time and UTC offset.
//
// Format Description
//
// A timestamp is composed of 3 components:
//
// - secs: signed integer representing seconds since unix epoch
// - nsces: unsigned integer representing fractional seconds as a
// nanosecond offset within secs, in the range 0 <= nsecs < 1e9
// - tz: signed integer representing timezone offset in minutes east of UTC,
// and a dst (daylight savings time) flag
//
// When encoding a timestamp, the first byte is the descriptor, which
// defines which components are encoded and how many bytes are used to
// encode secs and nsecs components. *If secs/nsecs is 0 or tz is UTC, it
// is not encoded in the byte array explicitly*.
//
// Descriptor 8 bits are of the form `A B C DDD EE`:
// A: Is secs component encoded? 1 = true
// B: Is nsecs component encoded? 1 = true
// C: Is tz component encoded? 1 = true
// DDD: Number of extra bytes for secs (range 0-7).
// If A = 1, secs encoded in DDD+1 bytes.
// If A = 0, secs is not encoded, and is assumed to be 0.
// If A = 1, then we need at least 1 byte to encode secs.
// DDD says the number of extra bytes beyond that 1.
// E.g. if DDD=0, then secs is represented in 1 byte.
// if DDD=2, then secs is represented in 3 bytes.
// EE: Number of extra bytes for nsecs (range 0-3).
// If B = 1, nsecs encoded in EE+1 bytes (similar to secs/DDD above)
//
// Following the descriptor bytes, subsequent bytes are:
//
// secs component encoded in `DDD + 1` bytes (if A == 1)
// nsecs component encoded in `EE + 1` bytes (if B == 1)
// tz component encoded in 2 bytes (if C == 1)
//
// secs and nsecs components are integers encoded in a BigEndian
// 2-complement encoding format.
//
// tz component is encoded as 2 bytes (16 bits). Most significant bit 15 to
// Least significant bit 0 are described below:
//
// Timezone offset has a range of -12:00 to +14:00 (ie -720 to +840 minutes).
// Bit 15 = have\_dst: set to 1 if we set the dst flag.
// Bit 14 = dst\_on: set to 1 if dst is in effect at the time, or 0 if not.
// Bits 13..0 = timezone offset in minutes. It is a signed integer in Big Endian format.
func bincEncodeTime(t time.Time) []byte {
// t := rv2i(rv).(time.Time)
tsecs, tnsecs := t.Unix(), t.Nanosecond()
var (
bd byte
bs [16]byte
i int = 1
)
l := t.Location()
if l == time.UTC {
l = nil
}
if tsecs != 0 {
bd = bd | 0x80
btmp := bigen.PutUint64(uint64(tsecs))
f := pruneSignExt(btmp[:], tsecs >= 0)
bd = bd | (byte(7-f) << 2)
copy(bs[i:], btmp[f:])
i = i + (8 - f)
}
if tnsecs != 0 {
bd = bd | 0x40
btmp := bigen.PutUint32(uint32(tnsecs))
f := pruneSignExt(btmp[:4], true)
bd = bd | byte(3-f)
copy(bs[i:], btmp[f:4])
i = i + (4 - f)
}
if l != nil {
bd = bd | 0x20
// Note that Go Libs do not give access to dst flag.
_, zoneOffset := t.Zone()
// zoneName, zoneOffset := t.Zone()
zoneOffset /= 60
z := uint16(zoneOffset)
btmp := bigen.PutUint16(z)
// clear dst flags
bs[i] = btmp[0] & 0x3f
bs[i+1] = btmp[1]
i = i + 2
}
bs[0] = bd
return bs[0:i]
}
// bincDecodeTime decodes a []byte into a time.Time.
func bincDecodeTime(bs []byte) (tt time.Time, err error) {
bd := bs[0]
var (
tsec int64
tnsec uint32
tz uint16
i byte = 1
i2 byte
n byte
)
if bd&(1<<7) != 0 {
var btmp [8]byte
n = ((bd >> 2) & 0x7) + 1
i2 = i + n
copy(btmp[8-n:], bs[i:i2])
// if first bit of bs[i] is set, then fill btmp[0..8-n] with 0xff (ie sign extend it)
if bs[i]&(1<<7) != 0 {
copy(btmp[0:8-n], bsAll0xff)
}
i = i2
tsec = int64(bigen.Uint64(btmp))
}
if bd&(1<<6) != 0 {
var btmp [4]byte
n = (bd & 0x3) + 1
i2 = i + n
copy(btmp[4-n:], bs[i:i2])
i = i2
tnsec = bigen.Uint32(btmp)
}
if bd&(1<<5) == 0 {
tt = time.Unix(tsec, int64(tnsec)).UTC()
return
}
// In stdlib time.Parse, when a date is parsed without a zone name, it uses "" as zone name.
// However, we need name here, so it can be shown when time is printf.d.
// Zone name is in form: UTC-08:00.
// Note that Go Libs do not give access to dst flag, so we ignore dst bits
tz = bigen.Uint16([2]byte{bs[i], bs[i+1]})
// sign extend sign bit into top 2 MSB (which were dst bits):
if tz&(1<<13) == 0 { // positive
tz = tz & 0x3fff //clear 2 MSBs: dst bits
} else { // negative
tz = tz | 0xc000 //set 2 MSBs: dst bits
}
tzint := int16(tz)
if tzint == 0 {
tt = time.Unix(tsec, int64(tnsec)).UTC()
} else {
// For Go Time, do not use a descriptive timezone.
// It's unnecessary, and makes it harder to do a reflect.DeepEqual.
// The Offset already tells what the offset should be, if not on UTC and unknown zone name.
// var zoneName = timeLocUTCName(tzint)
tt = time.Unix(tsec, int64(tnsec)).In(time.FixedZone("", int(tzint)*60))
}
return
}
var _ decDriver = (*bincDecDriver)(nil)
var _ encDriver = (*bincEncDriver)(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/ugorji/go/codec/0_importpath.go | vendor/github.com/ugorji/go/codec/0_importpath.go | // Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
package codec // import "github.com/ugorji/go/codec"
// This establishes that this package must be imported as github.com/ugorji/go/codec.
// It makes forking easier, and plays well with pre-module releases of go.
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ugorji/go/codec/gen.go | vendor/github.com/ugorji/go/codec/gen.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
//go:build codecgen.exec
// +build codecgen.exec
package codec
import (
"bytes"
"encoding/base32"
"errors"
"fmt"
"go/format"
"io"
"io/ioutil"
"math/rand"
"os"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"text/template"
"time"
// "ugorji.net/zz"
"unicode"
"unicode/utf8"
)
// ---------------------------------------------------
// codecgen supports the full cycle of reflection-based codec:
// - RawExt
// - Raw
// - Extensions
// - (Binary|Text|JSON)(Unm|M)arshal
// - generic by-kind
//
// This means that, for dynamic things, we MUST use reflection to at least get the reflect.Type.
// In those areas, we try to only do reflection or interface-conversion when NECESSARY:
// - Extensions, only if Extensions are configured.
//
// However, note following codecgen caveats:
// - Canonical option.
// If Canonical=true, codecgen'ed code may delegate encoding maps to reflection-based code.
// This is due to the runtime work needed to marshal a map in canonical mode.
// However, if map key is a pre-defined/builtin numeric or string type, codecgen
// will try to write it out itself
// - CheckCircularRef option.
// When encoding a struct, a circular reference can lead to a stack overflow.
// If CheckCircularRef=true, codecgen'ed code will delegate encoding structs to reflection-based code.
// - MissingFielder implementation.
// If a type implements MissingFielder, a Selfer is not generated (with a warning message).
// Statically reproducing the runtime work needed to extract the missing fields and marshal them
// along with the struct fields, while handling the Canonical=true special case, was onerous to implement.
//
// During encode/decode, Selfer takes precedence.
// A type implementing Selfer will know how to encode/decode itself statically.
//
// The following field types are supported:
// array: [n]T
// slice: []T
// map: map[K]V
// primitive: [u]int[n], float(32|64), bool, string
// struct
//
// ---------------------------------------------------
// Note that a Selfer cannot call (e|d).(En|De)code on itself,
// as this will cause a circular reference, as (En|De)code will call Selfer methods.
// Any type that implements Selfer must implement completely and not fallback to (En|De)code.
//
// In addition, code in this file manages the generation of fast-path implementations of
// encode/decode of slices/maps of primitive keys/values.
//
// Users MUST re-generate their implementations whenever the code shape changes.
// The generated code will panic if it was generated with a version older than the supporting library.
// ---------------------------------------------------
//
// codec framework is very feature rich.
// When encoding or decoding into an interface, it depends on the runtime type of the interface.
// The type of the interface may be a named type, an extension, etc.
// Consequently, we fallback to runtime codec for encoding/decoding interfaces.
// In addition, we fallback for any value which cannot be guaranteed at runtime.
// This allows us support ANY value, including any named types, specifically those which
// do not implement our interfaces (e.g. Selfer).
//
// This explains some slowness compared to other code generation codecs (e.g. msgp).
// This reduction in speed is only seen when your refers to interfaces,
// e.g. type T struct { A interface{}; B []interface{}; C map[string]interface{} }
//
// codecgen will panic if the file was generated with an old version of the library in use.
//
// Note:
// It was a conscious decision to have gen.go always explicitly call EncodeNil or TryDecodeAsNil.
// This way, there isn't a function call overhead just to see that we should not enter a block of code.
//
// Note:
// codecgen-generated code depends on the variables defined by fast-path.generated.go.
// consequently, you cannot run with tags "codecgen codec.notfastpath".
//
// Note:
// genInternalXXX functions are used for generating fast-path and other internally generated
// files, and not for use in codecgen.
// Size of a struct or value is not portable across machines, especially across 32-bit vs 64-bit
// operating systems. This is due to types like int, uintptr, pointers, (and derived types like slice), etc
// which use the natural word size on those machines, which may be 4 bytes (on 32-bit) or 8 bytes (on 64-bit).
//
// Within decInferLen calls, we may generate an explicit size of the entry.
// We do this because decInferLen values are expected to be approximate,
// and serve as a good hint on the size of the elements or key+value entry.
//
// Since development is done on 64-bit machines, the sizes will be roughly correctly
// on 64-bit OS, and slightly larger than expected on 32-bit OS.
// This is ok.
//
// For reference, look for 'Size' in fast-path.go.tmpl, gen-dec-(array|map).go.tmpl and gen.go (this file).
// GenVersion is the current version of codecgen.
//
// MARKER: Increment this value each time codecgen changes fundamentally.
// Also update codecgen/gen.go (minimumCodecVersion, genVersion, etc).
// Fundamental changes are:
// - helper methods change (signature change, new ones added, some removed, etc)
// - codecgen command line changes
//
// v1: Initial Version
// v2: -
// v3: For Kubernetes: changes in signature of some unpublished helper methods and codecgen cmdline arguments.
// v4: Removed separator support from (en|de)cDriver, and refactored codec(gen)
// v5: changes to support faster json decoding. Let encoder/decoder maintain state of collections.
// v6: removed unsafe from gen, and now uses codecgen.exec tag
// v7: -
// v8: current - we now maintain compatibility with old generated code.
// v9: - skipped
// v10: modified encDriver and decDriver interfaces.
// v11: remove deprecated methods of encDriver and decDriver.
// v12: removed deprecated methods from genHelper and changed container tracking logic
// v13: 20190603 removed DecodeString - use DecodeStringAsBytes instead
// v14: 20190611 refactored nil handling: TryDecodeAsNil -> selective TryNil, etc
// v15: 20190626 encDriver.EncodeString handles StringToRaw flag inside handle
// v16: 20190629 refactoring for v1.1.6
// v17: 20200911 reduce number of types for which we generate fast path functions (v1.1.8)
// v18: 20201004 changed definition of genHelper...Extension (to take interface{}) and eliminated I2Rtid method
// v19: 20201115 updated codecgen cmdline flags and optimized output
// v20: 20201120 refactored GenHelper to one exported function
// v21: 20210104 refactored generated code to honor ZeroCopy=true for more efficiency
// v22: 20210118 fixed issue in generated code when encoding a type which is also a codec.Selfer
// v23: 20210203 changed slice/map types for which we generate fast-path functions
// v24: 20210226 robust handling for Canonical|CheckCircularRef flags and MissingFielder implementations
// v25: 20210406 pass base reflect.Type to side(En|De)code and (En|De)codeExt calls
// v26: 20230201 genHelper changes for more inlining and consequent performance
// v27: 20230219 fix error decoding struct from array - due to misplaced counter increment
// v28: 20230224 fix decoding missing fields of struct from array, due to double counter increment
const genVersion = 28
const (
genCodecPkg = "codec1978" // MARKER: keep in sync with codecgen/gen.go
genTempVarPfx = "yy"
genTopLevelVarName = "x"
// ignore canBeNil parameter, and always set to true.
// This is because nil can appear anywhere, so we should always check.
genAnythingCanBeNil = true
// genStructCanonical configures whether we generate 2 paths based on Canonical flag
// when encoding struct fields.
genStructCanonical = true
// genFastpathCanonical configures whether we support Canonical in fast path.
// The savings is not much.
//
// MARKER: This MUST ALWAYS BE TRUE. fast-path.go.tmp doesn't handle it being false.
genFastpathCanonical = true
// genFastpathTrimTypes configures whether we trim uncommon fastpath types.
genFastpathTrimTypes = true
)
type genStringDecAsBytes string
type genStringDecZC string
var genStringDecAsBytesTyp = reflect.TypeOf(genStringDecAsBytes(""))
var genStringDecZCTyp = reflect.TypeOf(genStringDecZC(""))
var genFormats = []string{"Json", "Cbor", "Msgpack", "Binc", "Simple"}
var (
errGenAllTypesSamePkg = errors.New("All types must be in the same package")
errGenExpectArrayOrMap = errors.New("unexpected type - expecting array/map/slice")
errGenUnexpectedTypeFastpath = errors.New("fast-path: unexpected type - requires map or slice")
// don't use base64, only 63 characters allowed in valid go identifiers
// ie ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_
//
// don't use numbers, as a valid go identifer must start with a letter.
genTypenameEnc = base32.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef")
genQNameRegex = regexp.MustCompile(`[A-Za-z_.]+`)
)
type genBuf struct {
buf []byte
}
func (x *genBuf) sIf(b bool, s, t string) *genBuf {
if b {
x.buf = append(x.buf, s...)
} else {
x.buf = append(x.buf, t...)
}
return x
}
func (x *genBuf) s(s string) *genBuf { x.buf = append(x.buf, s...); return x }
func (x *genBuf) b(s []byte) *genBuf { x.buf = append(x.buf, s...); return x }
func (x *genBuf) v() string { return string(x.buf) }
func (x *genBuf) f(s string, args ...interface{}) { x.s(fmt.Sprintf(s, args...)) }
func (x *genBuf) reset() {
if x.buf != nil {
x.buf = x.buf[:0]
}
}
// genRunner holds some state used during a Gen run.
type genRunner struct {
w io.Writer // output
c uint64 // counter used for generating varsfx
f uint64 // counter used for saying false
t []reflect.Type // list of types to run selfer on
tc reflect.Type // currently running selfer on this type
te map[uintptr]bool // types for which the encoder has been created
td map[uintptr]bool // types for which the decoder has been created
tz map[uintptr]bool // types for which GenIsZero has been created
cp string // codec import path
im map[string]reflect.Type // imports to add
imn map[string]string // package names of imports to add
imc uint64 // counter for import numbers
is map[reflect.Type]struct{} // types seen during import search
bp string // base PkgPath, for which we are generating for
cpfx string // codec package prefix
ty map[reflect.Type]struct{} // types for which GenIsZero *should* be created
tm map[reflect.Type]struct{} // types for which enc/dec must be generated
ts []reflect.Type // types for which enc/dec must be generated
xs string // top level variable/constant suffix
hn string // fn helper type name
ti *TypeInfos
// rr *rand.Rand // random generator for file-specific types
jsonOnlyWhen, toArrayWhen, omitEmptyWhen *bool
nx bool // no extensions
}
type genIfClause struct {
hasIf bool
}
func (g *genIfClause) end(x *genRunner) {
if g.hasIf {
x.line("}")
}
}
func (g *genIfClause) c(last bool) (v string) {
if last {
if g.hasIf {
v = " } else { "
}
} else if g.hasIf {
v = " } else if "
} else {
v = "if "
g.hasIf = true
}
return
}
// Gen will write a complete go file containing Selfer implementations for each
// type passed. All the types must be in the same package.
//
// Library users: DO NOT USE IT DIRECTLY. IT WILL CHANGE CONTINUOUSLY WITHOUT NOTICE.
func Gen(w io.Writer, buildTags, pkgName, uid string, noExtensions bool,
jsonOnlyWhen, toArrayWhen, omitEmptyWhen *bool,
ti *TypeInfos, types ...reflect.Type) (warnings []string) {
// All types passed to this method do not have a codec.Selfer method implemented directly.
// codecgen already checks the AST and skips any types that define the codec.Selfer methods.
// Consequently, there's no need to check and trim them if they implement codec.Selfer
if len(types) == 0 {
return
}
x := genRunner{
w: w,
t: types,
te: make(map[uintptr]bool),
td: make(map[uintptr]bool),
tz: make(map[uintptr]bool),
im: make(map[string]reflect.Type),
imn: make(map[string]string),
is: make(map[reflect.Type]struct{}),
tm: make(map[reflect.Type]struct{}),
ty: make(map[reflect.Type]struct{}),
ts: []reflect.Type{},
bp: genImportPath(types[0]),
xs: uid,
ti: ti,
jsonOnlyWhen: jsonOnlyWhen,
toArrayWhen: toArrayWhen,
omitEmptyWhen: omitEmptyWhen,
nx: noExtensions,
}
if x.ti == nil {
x.ti = defTypeInfos
}
if x.xs == "" {
rr := rand.New(rand.NewSource(time.Now().UnixNano()))
x.xs = strconv.FormatInt(rr.Int63n(9999), 10)
}
// gather imports first:
x.cp = genImportPath(reflect.TypeOf(x))
x.imn[x.cp] = genCodecPkg
// iterate, check if all in same package, and remove any missingfielders
for i := 0; i < len(x.t); {
t := x.t[i]
// xdebugf("###########: PkgPath: '%v', Name: '%s'\n", genImportPath(t), t.Name())
if genImportPath(t) != x.bp {
halt.onerror(errGenAllTypesSamePkg)
}
ti1 := x.ti.get(rt2id(t), t)
if ti1.flagMissingFielder || ti1.flagMissingFielderPtr {
// output diagnostic message - that nothing generated for this type
warnings = append(warnings, fmt.Sprintf("type: '%v' not generated; implements codec.MissingFielder", t))
copy(x.t[i:], x.t[i+1:])
x.t = x.t[:len(x.t)-1]
continue
}
x.genRefPkgs(t)
i++
}
x.line("// +build go1.6")
if buildTags != "" {
x.line("// +build " + buildTags)
}
x.line(`
// Code generated by codecgen - DO NOT EDIT.
`)
x.line("package " + pkgName)
x.line("")
x.line("import (")
if x.cp != x.bp {
x.cpfx = genCodecPkg + "."
x.linef("%s \"%s\"", genCodecPkg, x.cp)
}
// use a sorted set of im keys, so that we can get consistent output
imKeys := make([]string, 0, len(x.im))
for k := range x.im {
imKeys = append(imKeys, k)
}
sort.Strings(imKeys)
for _, k := range imKeys { // for k, _ := range x.im {
if k == x.imn[k] {
x.linef("\"%s\"", k)
} else {
x.linef("%s \"%s\"", x.imn[k], k)
}
}
// add required packages
for _, k := range [...]string{"runtime", "errors", "strconv", "sort"} { // "reflect", "fmt"
if _, ok := x.im[k]; !ok {
x.line("\"" + k + "\"")
}
}
x.line(")")
x.line("")
x.line("const (")
x.linef("// ----- content types ----")
x.linef("codecSelferCcUTF8%s = %v", x.xs, int64(cUTF8))
x.linef("codecSelferCcRAW%s = %v", x.xs, int64(cRAW))
x.linef("// ----- value types used ----")
for _, vt := range [...]valueType{
valueTypeArray, valueTypeMap, valueTypeString,
valueTypeInt, valueTypeUint, valueTypeFloat,
valueTypeNil,
} {
x.linef("codecSelferValueType%s%s = %v", vt.String(), x.xs, int64(vt))
}
x.linef("codecSelferBitsize%s = uint8(32 << (^uint(0) >> 63))", x.xs)
x.linef("codecSelferDecContainerLenNil%s = %d", x.xs, int64(containerLenNil))
x.line(")")
x.line("var (")
x.line("errCodecSelferOnlyMapOrArrayEncodeToStruct" + x.xs + " = " + "errors.New(`only encoded map or array can be decoded into a struct`)")
x.line("_ sort.Interface = nil")
x.line(")")
x.line("")
x.hn = "codecSelfer" + x.xs
x.line("type " + x.hn + " struct{}")
x.line("")
x.linef("func %sFalse() bool { return false }", x.hn)
x.linef("func %sTrue() bool { return true }", x.hn)
x.line("")
// add types for sorting canonical
for _, s := range []string{"string", "uint64", "int64", "float64"} {
x.linef("type %s%sSlice []%s", x.hn, s, s)
x.linef("func (p %s%sSlice) Len() int { return len(p) }", x.hn, s)
x.linef("func (p %s%sSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] }", x.hn, s)
x.linef("func (p %s%sSlice) Less(i, j int) bool { return p[uint(i)] < p[uint(j)] }", x.hn, s)
}
x.line("")
x.varsfxreset()
x.line("func init() {")
x.linef("if %sGenVersion != %v {", x.cpfx, genVersion)
x.line("_, file, _, _ := runtime.Caller(0)")
x.linef("ver := strconv.FormatInt(int64(%sGenVersion), 10)", x.cpfx)
x.outf(`panic(errors.New("codecgen version mismatch: current: %v, need " + ver + ". Re-generate file: " + file))`, genVersion)
x.linef("}")
if len(imKeys) > 0 {
x.line("if false { // reference the types, but skip this branch at build/run time")
for _, k := range imKeys {
t := x.im[k]
x.linef("var _ %s.%s", x.imn[k], t.Name())
}
x.line("} ") // close if false
}
x.line("}") // close init
x.line("")
// generate rest of type info
for _, t := range x.t {
x.tc = t
x.linef("func (%s) codecSelferViaCodecgen() {}", x.genTypeName(t))
x.selfer(true)
x.selfer(false)
x.tryGenIsZero(t)
}
for _, t := range x.ts {
rtid := rt2id(t)
// generate enc functions for all these slice/map types.
x.varsfxreset()
x.linef("func (x %s) enc%s(v %s%s, e *%sEncoder) {", x.hn, x.genMethodNameT(t), x.arr2str(t, "*"), x.genTypeName(t), x.cpfx)
x.genRequiredMethodVars(true)
switch t.Kind() {
case reflect.Array, reflect.Slice, reflect.Chan:
x.encListFallback("v", t)
case reflect.Map:
x.encMapFallback("v", t)
default:
halt.onerror(errGenExpectArrayOrMap)
}
x.line("}")
x.line("")
// generate dec functions for all these slice/map types.
x.varsfxreset()
x.linef("func (x %s) dec%s(v *%s, d *%sDecoder) {", x.hn, x.genMethodNameT(t), x.genTypeName(t), x.cpfx)
x.genRequiredMethodVars(false)
switch t.Kind() {
case reflect.Array, reflect.Slice, reflect.Chan:
x.decListFallback("v", rtid, t)
case reflect.Map:
x.decMapFallback("v", rtid, t)
default:
halt.onerror(errGenExpectArrayOrMap)
}
x.line("}")
x.line("")
}
for t := range x.ty {
x.tryGenIsZero(t)
x.line("")
}
x.line("")
return
}
func (x *genRunner) checkForSelfer(t reflect.Type, varname string) bool {
// return varname != genTopLevelVarName && t != x.tc
// the only time we checkForSelfer is if we are not at the TOP of the generated code.
return varname != genTopLevelVarName
}
func (x *genRunner) arr2str(t reflect.Type, s string) string {
if t.Kind() == reflect.Array {
return s
}
return ""
}
func (x *genRunner) genRequiredMethodVars(encode bool) {
x.line("var h " + x.hn)
if encode {
x.line("z, r := " + x.cpfx + "GenHelper().Encoder(e)")
} else {
x.line("z, r := " + x.cpfx + "GenHelper().Decoder(d)")
}
x.line("_, _, _ = h, z, r")
}
func (x *genRunner) genRefPkgs(t reflect.Type) {
if _, ok := x.is[t]; ok {
return
}
x.is[t] = struct{}{}
tpkg, tname := genImportPath(t), t.Name()
if tpkg != "" && tpkg != x.bp && tpkg != x.cp && tname != "" && tname[0] >= 'A' && tname[0] <= 'Z' {
if _, ok := x.im[tpkg]; !ok {
x.im[tpkg] = t
if idx := strings.LastIndex(tpkg, "/"); idx < 0 {
x.imn[tpkg] = tpkg
} else {
x.imc++
x.imn[tpkg] = "pkg" + strconv.FormatUint(x.imc, 10) + "_" + genGoIdentifier(tpkg[idx+1:], false)
}
}
}
switch t.Kind() {
case reflect.Array, reflect.Slice, reflect.Ptr, reflect.Chan:
x.genRefPkgs(t.Elem())
case reflect.Map:
x.genRefPkgs(t.Elem())
x.genRefPkgs(t.Key())
case reflect.Struct:
for i := 0; i < t.NumField(); i++ {
if fname := t.Field(i).Name; fname != "" && fname[0] >= 'A' && fname[0] <= 'Z' {
x.genRefPkgs(t.Field(i).Type)
}
}
}
}
// sayFalse will either say "false" or use a function call that returns false.
func (x *genRunner) sayFalse() string {
x.f++
if x.f%2 == 0 {
return x.hn + "False()"
}
return "false"
}
// sayFalse will either say "true" or use a function call that returns true.
func (x *genRunner) sayTrue() string {
x.f++
if x.f%2 == 0 {
return x.hn + "True()"
}
return "true"
}
func (x *genRunner) varsfx() string {
x.c++
return strconv.FormatUint(x.c, 10)
}
func (x *genRunner) varsfxreset() {
x.c = 0
}
func (x *genRunner) out(s string) {
_, err := io.WriteString(x.w, s)
genCheckErr(err)
}
func (x *genRunner) outf(s string, params ...interface{}) {
_, err := fmt.Fprintf(x.w, s, params...)
genCheckErr(err)
}
func (x *genRunner) line(s string) {
x.out(s)
if len(s) == 0 || s[len(s)-1] != '\n' {
x.out("\n")
}
}
func (x *genRunner) lineIf(s string) {
if s != "" {
x.line(s)
}
}
func (x *genRunner) linef(s string, params ...interface{}) {
x.outf(s, params...)
if len(s) == 0 || s[len(s)-1] != '\n' {
x.out("\n")
}
}
func (x *genRunner) genTypeName(t reflect.Type) (n string) {
// if the type has a PkgPath, which doesn't match the current package,
// then include it.
// We cannot depend on t.String() because it includes current package,
// or t.PkgPath because it includes full import path,
//
var ptrPfx string
for t.Kind() == reflect.Ptr {
ptrPfx += "*"
t = t.Elem()
}
if tn := t.Name(); tn != "" {
return ptrPfx + x.genTypeNamePrim(t)
}
switch t.Kind() {
case reflect.Map:
return ptrPfx + "map[" + x.genTypeName(t.Key()) + "]" + x.genTypeName(t.Elem())
case reflect.Slice:
return ptrPfx + "[]" + x.genTypeName(t.Elem())
case reflect.Array:
return ptrPfx + "[" + strconv.FormatInt(int64(t.Len()), 10) + "]" + x.genTypeName(t.Elem())
case reflect.Chan:
return ptrPfx + t.ChanDir().String() + " " + x.genTypeName(t.Elem())
default:
if t == intfTyp {
return ptrPfx + "interface{}"
} else {
return ptrPfx + x.genTypeNamePrim(t)
}
}
}
func (x *genRunner) genTypeNamePrim(t reflect.Type) (n string) {
if t.Name() == "" {
return t.String()
} else if genImportPath(t) == "" || genImportPath(t) == genImportPath(x.tc) {
return t.Name()
} else {
return x.imn[genImportPath(t)] + "." + t.Name()
// return t.String() // best way to get the package name inclusive
}
}
func (x *genRunner) genZeroValueR(t reflect.Type) string {
// if t is a named type, w
switch t.Kind() {
case reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func,
reflect.Slice, reflect.Map, reflect.Invalid:
return "nil"
case reflect.Bool:
return "false"
case reflect.String:
return `""`
case reflect.Struct, reflect.Array:
return x.genTypeName(t) + "{}"
default: // all numbers
return "0"
}
}
func (x *genRunner) genMethodNameT(t reflect.Type) (s string) {
return genMethodNameT(t, x.tc)
}
func (x *genRunner) tryGenIsZero(t reflect.Type) (done bool) {
if t.Kind() != reflect.Struct || t.Implements(isCodecEmptyerTyp) {
return
}
rtid := rt2id(t)
if _, ok := x.tz[rtid]; ok {
delete(x.ty, t)
return
}
x.tz[rtid] = true
delete(x.ty, t)
ti := x.ti.get(rtid, t)
tisfi := ti.sfi.source() // always use sequence from file. decStruct expects same thing.
varname := genTopLevelVarName
x.linef("func (%s *%s) IsCodecEmpty() bool {", varname, x.genTypeName(t))
anonSeen := make(map[reflect.Type]bool)
var omitline genBuf
for _, si := range tisfi {
if si.path.parent != nil {
root := si.path.root()
if anonSeen[root.typ] {
continue
}
anonSeen[root.typ] = true
}
t2 := genOmitEmptyLinePreChecks(varname, t, si, &omitline, true)
// if Ptr, we already checked if nil above
if t2.Type.Kind() != reflect.Ptr {
x.doEncOmitEmptyLine(t2, varname, &omitline)
omitline.s(" || ")
}
}
omitline.s(" false")
x.linef("return !(%s)", omitline.v())
x.line("}")
x.line("")
return true
}
func (x *genRunner) selfer(encode bool) {
t := x.tc
// ti := x.ti.get(rt2id(t), t)
t0 := t
// always make decode use a pointer receiver,
// and structs/arrays always use a ptr receiver (encode|decode)
isptr := !encode || t.Kind() == reflect.Array || (t.Kind() == reflect.Struct && t != timeTyp)
x.varsfxreset()
fnSigPfx := "func (" + genTopLevelVarName + " "
if isptr {
fnSigPfx += "*"
}
fnSigPfx += x.genTypeName(t)
x.out(fnSigPfx)
if isptr {
t = reflect.PtrTo(t)
}
if encode {
x.line(") CodecEncodeSelf(e *" + x.cpfx + "Encoder) {")
x.genRequiredMethodVars(true)
if t0.Kind() == reflect.Struct {
x.linef("if z.EncBasicHandle().CheckCircularRef { z.EncEncode(%s); return }", genTopLevelVarName)
}
x.encVar(genTopLevelVarName, t)
} else {
x.line(") CodecDecodeSelf(d *" + x.cpfx + "Decoder) {")
x.genRequiredMethodVars(false)
// do not use decVar, as there is no need to check TryDecodeAsNil
// or way to elegantly handle that, and also setting it to a
// non-nil value doesn't affect the pointer passed.
// x.decVar(genTopLevelVarName, t, false)
x.dec(genTopLevelVarName, t0, true)
}
x.line("}")
x.line("")
if encode || t0.Kind() != reflect.Struct {
return
}
// write is containerMap
x.out(fnSigPfx)
x.line(") codecDecodeSelfFromMap(l int, d *" + x.cpfx + "Decoder) {")
x.genRequiredMethodVars(false)
x.decStructMap(genTopLevelVarName, "l", rt2id(t0), t0)
x.line("}")
x.line("")
// write containerArray
x.out(fnSigPfx)
x.line(") codecDecodeSelfFromArray(l int, d *" + x.cpfx + "Decoder) {")
x.genRequiredMethodVars(false)
x.decStructArray(genTopLevelVarName, "l", "return", rt2id(t0), t0)
x.line("}")
x.line("")
}
// used for chan, array, slice, map
func (x *genRunner) xtraSM(varname string, t reflect.Type, ti *typeInfo, encode, isptr bool) {
var ptrPfx, addrPfx string
if isptr {
ptrPfx = "*"
} else {
addrPfx = "&"
}
if encode {
x.linef("h.enc%s((%s%s)(%s), e)", x.genMethodNameT(t), ptrPfx, x.genTypeName(t), varname)
} else {
x.linef("h.dec%s((*%s)(%s%s), d)", x.genMethodNameT(t), x.genTypeName(t), addrPfx, varname)
}
x.registerXtraT(t, ti)
}
func (x *genRunner) registerXtraT(t reflect.Type, ti *typeInfo) {
// recursively register the types
tk := t.Kind()
if tk == reflect.Ptr {
x.registerXtraT(t.Elem(), nil)
return
}
if _, ok := x.tm[t]; ok {
return
}
switch tk {
case reflect.Chan, reflect.Slice, reflect.Array, reflect.Map:
default:
return
}
// only register the type if it will not default to a fast-path
if ti == nil {
ti = x.ti.get(rt2id(t), t)
}
if _, rtidu := genFastpathUnderlying(t, ti.rtid, ti); fastpathAvIndex(rtidu) != -1 {
return
}
x.tm[t] = struct{}{}
x.ts = append(x.ts, t)
// check if this refers to any xtra types eg. a slice of array: add the array
x.registerXtraT(t.Elem(), nil)
if tk == reflect.Map {
x.registerXtraT(t.Key(), nil)
}
}
// encVar will encode a variable.
// The parameter, t, is the reflect.Type of the variable itself
func (x *genRunner) encVar(varname string, t reflect.Type) {
var checkNil bool
// case reflect.Ptr, reflect.Interface, reflect.Slice, reflect.Map, reflect.Chan:
// do not include checkNil for slice and maps, as we already checkNil below it
switch t.Kind() {
case reflect.Ptr, reflect.Interface, reflect.Chan:
checkNil = true
}
x.encVarChkNil(varname, t, checkNil)
}
func (x *genRunner) encVarChkNil(varname string, t reflect.Type, checkNil bool) {
if checkNil {
x.linef("if %s == nil { r.EncodeNil() } else {", varname)
}
switch t.Kind() {
case reflect.Ptr:
telem := t.Elem()
tek := telem.Kind()
if tek == reflect.Array || (tek == reflect.Struct && telem != timeTyp) {
x.enc(varname, genNonPtr(t), true)
break
}
i := x.varsfx()
x.line(genTempVarPfx + i + " := *" + varname)
x.enc(genTempVarPfx+i, genNonPtr(t), false)
case reflect.Struct, reflect.Array:
if t == timeTyp {
x.enc(varname, t, false)
break
}
i := x.varsfx()
x.line(genTempVarPfx + i + " := &" + varname)
x.enc(genTempVarPfx+i, t, true)
default:
x.enc(varname, t, false)
}
if checkNil {
x.line("}")
}
}
// enc will encode a variable (varname) of type t, where t represents T.
// if t is !time.Time and t is of kind reflect.Struct or reflect.Array, varname is of type *T
// (to prevent copying),
// else t is of type T
func (x *genRunner) enc(varname string, t reflect.Type, isptr bool) {
rtid := rt2id(t)
ti2 := x.ti.get(rtid, t)
// We call CodecEncodeSelf if one of the following are honored:
// - the type already implements Selfer, call that
// - the type has a Selfer implementation just created, use that
// - the type is in the list of the ones we will generate for, but it is not currently being generated
mi := x.varsfx()
// tptr := reflect.PtrTo(t)
// tk := t.Kind()
// check if
// - type is time.Time, RawExt, Raw
// - the type implements (Text|JSON|Binary)(Unm|M)arshal
var hasIf genIfClause
defer hasIf.end(x) // end if block (if necessary)
var ptrPfx, addrPfx string
if isptr {
ptrPfx = "*"
} else {
addrPfx = "&"
}
if t == timeTyp {
x.linef("%s z.EncBasicHandle().TimeBuiltin() { r.EncodeTime(%s%s)", hasIf.c(false), ptrPfx, varname)
// return
}
if t == rawTyp {
x.linef("%s z.EncRaw(%s%s)", hasIf.c(true), ptrPfx, varname)
return
}
if t == rawExtTyp {
x.linef("%s r.EncodeRawExt(%s%s)", hasIf.c(true), addrPfx, varname)
return
}
// only check for extensions if extensions are configured,
// and the type is named, and has a packagePath,
// and this is not the CodecEncodeSelf or CodecDecodeSelf method (i.e. it is not a Selfer)
if !x.nx && varname != genTopLevelVarName && t != genStringDecAsBytesTyp &&
t != genStringDecZCTyp && genImportPath(t) != "" && t.Name() != "" {
yy := fmt.Sprintf("%sxt%s", genTempVarPfx, mi)
x.linef("%s %s := z.Extension(%s); %s != nil { z.EncExtension(%s, %s) ",
hasIf.c(false), yy, varname, yy, varname, yy)
}
if x.checkForSelfer(t, varname) {
if ti2.flagSelfer {
x.linef("%s %s.CodecEncodeSelf(e)", hasIf.c(true), varname)
return
}
if ti2.flagSelferPtr {
if isptr {
x.linef("%s %s.CodecEncodeSelf(e)", hasIf.c(true), varname)
} else {
x.linef("%s %ssf%s := &%s", hasIf.c(true), genTempVarPfx, mi, varname)
x.linef("%ssf%s.CodecEncodeSelf(e)", genTempVarPfx, mi)
}
return
}
if _, ok := x.te[rtid]; ok {
x.linef("%s %s.CodecEncodeSelf(e)", hasIf.c(true), varname)
return
}
}
inlist := false
for _, t0 := range x.t {
if t == t0 {
inlist = true
if x.checkForSelfer(t, varname) {
x.linef("%s %s.CodecEncodeSelf(e)", hasIf.c(true), varname)
return
}
break
}
}
var rtidAdded bool
if t == x.tc {
x.te[rtid] = true
rtidAdded = true
}
if ti2.flagBinaryMarshaler {
x.linef("%s z.EncBinary() { z.EncBinaryMarshal(%s%v) ", hasIf.c(false), ptrPfx, varname)
} else if ti2.flagBinaryMarshalerPtr {
x.linef("%s z.EncBinary() { z.EncBinaryMarshal(%s%v) ", hasIf.c(false), addrPfx, varname)
}
if ti2.flagJsonMarshaler {
x.linef("%s !z.EncBinary() && z.IsJSONHandle() { z.EncJSONMarshal(%s%v) ", hasIf.c(false), ptrPfx, varname)
} else if ti2.flagJsonMarshalerPtr {
x.linef("%s !z.EncBinary() && z.IsJSONHandle() { z.EncJSONMarshal(%s%v) ", hasIf.c(false), addrPfx, varname)
} else if ti2.flagTextMarshaler {
x.linef("%s !z.EncBinary() { z.EncTextMarshal(%s%v) ", hasIf.c(false), ptrPfx, varname)
} else if ti2.flagTextMarshalerPtr {
x.linef("%s !z.EncBinary() { z.EncTextMarshal(%s%v) ", hasIf.c(false), addrPfx, varname)
}
x.lineIf(hasIf.c(true))
switch t.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
x.line("r.EncodeInt(int64(" + varname + "))")
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
x.line("r.EncodeUint(uint64(" + varname + "))")
case reflect.Float32:
x.line("r.EncodeFloat32(float32(" + varname + "))")
case reflect.Float64:
x.line("r.EncodeFloat64(float64(" + varname + "))")
case reflect.Complex64:
x.linef("z.EncEncodeComplex64(complex64(%s))", varname)
case reflect.Complex128:
x.linef("z.EncEncodeComplex128(complex128(%s))", varname)
case reflect.Bool:
x.line("r.EncodeBool(bool(" + varname + "))")
case reflect.String:
x.linef("r.EncodeString(string(%s))", varname)
case reflect.Chan:
x.xtraSM(varname, t, ti2, true, false)
// x.encListFallback(varname, rtid, t)
case reflect.Array:
_, rtidu := genFastpathUnderlying(t, rtid, ti2)
if fastpathAvIndex(rtidu) != -1 {
g := x.newFastpathGenV(ti2.key)
x.linef("z.F.%sV((%s)(%s[:]), e)", g.MethodNamePfx("Enc", false), x.genTypeName(ti2.key), varname)
} else {
x.xtraSM(varname, t, ti2, true, true)
}
case reflect.Slice:
// if nil, call dedicated function
// if a []byte, call dedicated function
// if a known fastpath slice, call dedicated function
// else write encode function in-line.
// - if elements are primitives or Selfers, call dedicated function on each member.
// - else call Encoder.encode(XXX) on it.
x.linef("if %s == nil { r.EncodeNil() } else {", varname)
if rtid == uint8SliceTypId {
x.line("r.EncodeStringBytesRaw([]byte(" + varname + "))")
} else {
tu, rtidu := genFastpathUnderlying(t, rtid, ti2)
if fastpathAvIndex(rtidu) != -1 {
g := x.newFastpathGenV(tu)
if rtid == rtidu {
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | true |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ugorji/go/codec/helper_not_unsafe_not_gc.go | vendor/github.com/ugorji/go/codec/helper_not_unsafe_not_gc.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
//go:build !go1.9 || safe || codec.safe || appengine || !gc
// +build !go1.9 safe codec.safe appengine !gc
package codec
// import "reflect"
// This files contains safe versions of the code where the unsafe versions are not supported
// in either gccgo or gollvm.
//
// - rvType:
// reflect.toType is not supported in gccgo, gollvm.
// func rvType(rv reflect.Value) reflect.Type {
// return rv.Type()
// }
var _ = 0
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ugorji/go/codec/helper_unsafe.go | vendor/github.com/ugorji/go/codec/helper_unsafe.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
//go:build !safe && !codec.safe && !appengine && go1.9
// +build !safe,!codec.safe,!appengine,go1.9
// minimum of go 1.9 is needed, as that is the minimum for all features and linked functions we need
// - typedmemclr was introduced in go 1.8
// - mapassign_fastXXX was introduced in go 1.9
// etc
package codec
import (
"reflect"
_ "runtime" // needed for go linkname(s)
"sync/atomic"
"time"
"unsafe"
)
// This file has unsafe variants of some helper functions.
// MARKER: See helper_unsafe.go for the usage documentation.
// There are a number of helper_*unsafe*.go files.
//
// - helper_unsafe
// unsafe variants of dependent functions
// - helper_unsafe_compiler_gc (gc)
// unsafe variants of dependent functions which cannot be shared with gollvm or gccgo
// - helper_not_unsafe_not_gc (gccgo/gollvm or safe)
// safe variants of functions in helper_unsafe_compiler_gc
// - helper_not_unsafe (safe)
// safe variants of functions in helper_unsafe
// - helper_unsafe_compiler_not_gc (gccgo, gollvm)
// unsafe variants of functions/variables which non-standard compilers need
//
// This way, we can judiciously use build tags to include the right set of files
// for any compiler, and make it run optimally in unsafe mode.
//
// As of March 2021, we cannot differentiate whether running with gccgo or gollvm
// using a build constraint, as both satisfy 'gccgo' build tag.
// Consequently, we must use the lowest common denominator to support both.
// For reflect.Value code, we decided to do the following:
// - if we know the kind, we can elide conditional checks for
// - SetXXX (Int, Uint, String, Bool, etc)
// - SetLen
//
// We can also optimize
// - IsNil
// MARKER: Some functions here will not be hit during code coverage runs due to optimizations, e.g.
// - rvCopySlice: called by decode if rvGrowSlice did not set new slice into pointer to orig slice.
// however, helper_unsafe sets it, so no need to call rvCopySlice later
// - rvSlice: same as above
const safeMode = false
// helperUnsafeDirectAssignMapEntry says that we should not copy the pointer in the map
// to another value during mapRange/iteration and mapGet calls, but directly assign it.
//
// The only callers of mapRange/iteration is encode.
// Here, we just walk through the values and encode them
//
// The only caller of mapGet is decode.
// Here, it does a Get if the underlying value is a pointer, and decodes into that.
//
// For both users, we are very careful NOT to modify or keep the pointers around.
// Consequently, it is ok for take advantage of the performance that the map is not modified
// during an iteration and we can just "peek" at the internal value" in the map and use it.
const helperUnsafeDirectAssignMapEntry = true
// MARKER: keep in sync with GO_ROOT/src/reflect/value.go
const (
unsafeFlagStickyRO = 1 << 5
unsafeFlagEmbedRO = 1 << 6
unsafeFlagIndir = 1 << 7
unsafeFlagAddr = 1 << 8
unsafeFlagRO = unsafeFlagStickyRO | unsafeFlagEmbedRO
// unsafeFlagKindMask = (1 << 5) - 1 // 5 bits for 27 kinds (up to 31)
// unsafeTypeKindDirectIface = 1 << 5
)
// transientSizeMax below is used in TransientAddr as the backing storage.
//
// Must be >= 16 as the maximum size is a complex128 (or string on 64-bit machines).
const transientSizeMax = 64
// should struct/array support internal strings and slices?
const transientValueHasStringSlice = false
type unsafeString struct {
Data unsafe.Pointer
Len int
}
type unsafeSlice struct {
Data unsafe.Pointer
Len int
Cap int
}
type unsafeIntf struct {
typ unsafe.Pointer
ptr unsafe.Pointer
}
type unsafeReflectValue struct {
unsafeIntf
flag uintptr
}
// keep in sync with stdlib runtime/type.go
type unsafeRuntimeType struct {
size uintptr
// ... many other fields here
}
// unsafeZeroAddr and unsafeZeroSlice points to a read-only block of memory
// used for setting a zero value for most types or creating a read-only
// zero value for a given type.
var (
unsafeZeroAddr = unsafe.Pointer(&unsafeZeroArr[0])
unsafeZeroSlice = unsafeSlice{unsafeZeroAddr, 0, 0}
)
// We use a scratch memory and an unsafeSlice for transient values:
//
// unsafeSlice is used for standalone strings and slices (outside an array or struct).
// scratch memory is used for other kinds, based on contract below:
// - numbers, bool are always transient
// - structs and arrays are transient iff they have no pointers i.e.
// no string, slice, chan, func, interface, map, etc only numbers and bools.
// - slices and strings are transient (using the unsafeSlice)
type unsafePerTypeElem struct {
arr [transientSizeMax]byte // for bool, number, struct, array kinds
slice unsafeSlice // for string and slice kinds
}
func (x *unsafePerTypeElem) addrFor(k reflect.Kind) unsafe.Pointer {
if k == reflect.String || k == reflect.Slice {
x.slice = unsafeSlice{} // memclr
return unsafe.Pointer(&x.slice)
}
x.arr = [transientSizeMax]byte{} // memclr
return unsafe.Pointer(&x.arr)
}
type perType struct {
elems [2]unsafePerTypeElem
}
type decPerType struct {
perType
}
type encPerType struct{}
// TransientAddrK is used for getting a *transient* value to be decoded into,
// which will right away be used for something else.
//
// See notes in helper.go about "Transient values during decoding"
func (x *perType) TransientAddrK(t reflect.Type, k reflect.Kind) reflect.Value {
return rvZeroAddrTransientAnyK(t, k, x.elems[0].addrFor(k))
}
func (x *perType) TransientAddr2K(t reflect.Type, k reflect.Kind) reflect.Value {
return rvZeroAddrTransientAnyK(t, k, x.elems[1].addrFor(k))
}
func (encPerType) AddressableRO(v reflect.Value) reflect.Value {
return rvAddressableReadonly(v)
}
// byteAt returns the byte given an index which is guaranteed
// to be within the bounds of the slice i.e. we defensively
// already verified that the index is less than the length of the slice.
func byteAt(b []byte, index uint) byte {
// return b[index]
return *(*byte)(unsafe.Pointer(uintptr((*unsafeSlice)(unsafe.Pointer(&b)).Data) + uintptr(index)))
}
func byteSliceOf(b []byte, start, end uint) []byte {
s := (*unsafeSlice)(unsafe.Pointer(&b))
s.Data = unsafe.Pointer(uintptr(s.Data) + uintptr(start))
s.Len = int(end - start)
s.Cap -= int(start)
return b
}
// func byteSliceWithLen(b []byte, length uint) []byte {
// (*unsafeSlice)(unsafe.Pointer(&b)).Len = int(length)
// return b
// }
func setByteAt(b []byte, index uint, val byte) {
// b[index] = val
*(*byte)(unsafe.Pointer(uintptr((*unsafeSlice)(unsafe.Pointer(&b)).Data) + uintptr(index))) = val
}
// stringView returns a view of the []byte as a string.
// In unsafe mode, it doesn't incur allocation and copying caused by conversion.
// In regular safe mode, it is an allocation and copy.
func stringView(v []byte) string {
return *(*string)(unsafe.Pointer(&v))
}
// bytesView returns a view of the string as a []byte.
// In unsafe mode, it doesn't incur allocation and copying caused by conversion.
// In regular safe mode, it is an allocation and copy.
func bytesView(v string) (b []byte) {
sx := (*unsafeString)(unsafe.Pointer(&v))
bx := (*unsafeSlice)(unsafe.Pointer(&b))
bx.Data, bx.Len, bx.Cap = sx.Data, sx.Len, sx.Len
return
}
func byteSliceSameData(v1 []byte, v2 []byte) bool {
return (*unsafeSlice)(unsafe.Pointer(&v1)).Data == (*unsafeSlice)(unsafe.Pointer(&v2)).Data
}
// MARKER: okBytesN functions will copy N bytes into the top slots of the return array.
// These functions expect that the bound check already occured and are are valid.
// copy(...) does a number of checks which are unnecessary in this situation when in bounds.
func okBytes2(b []byte) [2]byte {
return *((*[2]byte)(((*unsafeSlice)(unsafe.Pointer(&b))).Data))
}
func okBytes3(b []byte) [3]byte {
return *((*[3]byte)(((*unsafeSlice)(unsafe.Pointer(&b))).Data))
}
func okBytes4(b []byte) [4]byte {
return *((*[4]byte)(((*unsafeSlice)(unsafe.Pointer(&b))).Data))
}
func okBytes8(b []byte) [8]byte {
return *((*[8]byte)(((*unsafeSlice)(unsafe.Pointer(&b))).Data))
}
// isNil says whether the value v is nil.
// This applies to references like map/ptr/unsafepointer/chan/func,
// and non-reference values like interface/slice.
func isNil(v interface{}) (rv reflect.Value, isnil bool) {
var ui = (*unsafeIntf)(unsafe.Pointer(&v))
isnil = ui.ptr == nil
if !isnil {
rv, isnil = unsafeIsNilIntfOrSlice(ui, v)
}
return
}
func unsafeIsNilIntfOrSlice(ui *unsafeIntf, v interface{}) (rv reflect.Value, isnil bool) {
rv = reflect.ValueOf(v) // reflect.ValueOf is currently not inline'able - so call it directly
tk := rv.Kind()
isnil = (tk == reflect.Interface || tk == reflect.Slice) && *(*unsafe.Pointer)(ui.ptr) == nil
return
}
// return the pointer for a reference (map/chan/func/pointer/unsafe.Pointer).
// true references (map, func, chan, ptr - NOT slice) may be double-referenced? as flagIndir
//
// Assumes that v is a reference (map/func/chan/ptr/func)
func rvRefPtr(v *unsafeReflectValue) unsafe.Pointer {
if v.flag&unsafeFlagIndir != 0 {
return *(*unsafe.Pointer)(v.ptr)
}
return v.ptr
}
func eq4i(i0, i1 interface{}) bool {
v0 := (*unsafeIntf)(unsafe.Pointer(&i0))
v1 := (*unsafeIntf)(unsafe.Pointer(&i1))
return v0.typ == v1.typ && v0.ptr == v1.ptr
}
func rv4iptr(i interface{}) (v reflect.Value) {
// Main advantage here is that it is inlined, nothing escapes to heap, i is never nil
uv := (*unsafeReflectValue)(unsafe.Pointer(&v))
uv.unsafeIntf = *(*unsafeIntf)(unsafe.Pointer(&i))
uv.flag = uintptr(rkindPtr)
return
}
func rv4istr(i interface{}) (v reflect.Value) {
// Main advantage here is that it is inlined, nothing escapes to heap, i is never nil
uv := (*unsafeReflectValue)(unsafe.Pointer(&v))
uv.unsafeIntf = *(*unsafeIntf)(unsafe.Pointer(&i))
uv.flag = uintptr(rkindString) | unsafeFlagIndir
return
}
func rv2i(rv reflect.Value) (i interface{}) {
// We tap into implememtation details from
// the source go stdlib reflect/value.go, and trims the implementation.
//
// e.g.
// - a map/ptr is a reference, thus flagIndir is not set on it
// - an int/slice is not a reference, thus flagIndir is set on it
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
if refBitset.isset(byte(rv.Kind())) && urv.flag&unsafeFlagIndir != 0 {
urv.ptr = *(*unsafe.Pointer)(urv.ptr)
}
return *(*interface{})(unsafe.Pointer(&urv.unsafeIntf))
}
func rvAddr(rv reflect.Value, ptrType reflect.Type) reflect.Value {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
urv.flag = (urv.flag & unsafeFlagRO) | uintptr(reflect.Ptr)
urv.typ = ((*unsafeIntf)(unsafe.Pointer(&ptrType))).ptr
return rv
}
func rvIsNil(rv reflect.Value) bool {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
if urv.flag&unsafeFlagIndir != 0 {
return *(*unsafe.Pointer)(urv.ptr) == nil
}
return urv.ptr == nil
}
func rvSetSliceLen(rv reflect.Value, length int) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
(*unsafeString)(urv.ptr).Len = length
}
func rvZeroAddrK(t reflect.Type, k reflect.Kind) (rv reflect.Value) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
urv.typ = ((*unsafeIntf)(unsafe.Pointer(&t))).ptr
urv.flag = uintptr(k) | unsafeFlagIndir | unsafeFlagAddr
urv.ptr = unsafeNew(urv.typ)
return
}
func rvZeroAddrTransientAnyK(t reflect.Type, k reflect.Kind, addr unsafe.Pointer) (rv reflect.Value) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
urv.typ = ((*unsafeIntf)(unsafe.Pointer(&t))).ptr
urv.flag = uintptr(k) | unsafeFlagIndir | unsafeFlagAddr
urv.ptr = addr
return
}
func rvZeroK(t reflect.Type, k reflect.Kind) (rv reflect.Value) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
urv.typ = ((*unsafeIntf)(unsafe.Pointer(&t))).ptr
if refBitset.isset(byte(k)) {
urv.flag = uintptr(k)
} else if rtsize2(urv.typ) <= uintptr(len(unsafeZeroArr)) {
urv.flag = uintptr(k) | unsafeFlagIndir
urv.ptr = unsafeZeroAddr
} else { // meaning struct or array
urv.flag = uintptr(k) | unsafeFlagIndir | unsafeFlagAddr
urv.ptr = unsafeNew(urv.typ)
}
return
}
// rvConvert will convert a value to a different type directly,
// ensuring that they still point to the same underlying value.
func rvConvert(v reflect.Value, t reflect.Type) reflect.Value {
uv := (*unsafeReflectValue)(unsafe.Pointer(&v))
uv.typ = ((*unsafeIntf)(unsafe.Pointer(&t))).ptr
return v
}
// rvAddressableReadonly returns an addressable reflect.Value.
//
// Use it within encode calls, when you just want to "read" the underlying ptr
// without modifying the value.
//
// Note that it cannot be used for r/w use, as those non-addressable values
// may have been stored in read-only memory, and trying to write the pointer
// may cause a segfault.
func rvAddressableReadonly(v reflect.Value) reflect.Value {
// hack to make an addressable value out of a non-addressable one.
// Assume folks calling it are passing a value that can be addressable, but isn't.
// This assumes that the flagIndir is already set on it.
// so we just set the flagAddr bit on the flag (and do not set the flagIndir).
uv := (*unsafeReflectValue)(unsafe.Pointer(&v))
uv.flag = uv.flag | unsafeFlagAddr // | unsafeFlagIndir
return v
}
func rtsize2(rt unsafe.Pointer) uintptr {
return ((*unsafeRuntimeType)(rt)).size
}
func rt2id(rt reflect.Type) uintptr {
return uintptr(((*unsafeIntf)(unsafe.Pointer(&rt))).ptr)
}
func i2rtid(i interface{}) uintptr {
return uintptr(((*unsafeIntf)(unsafe.Pointer(&i))).typ)
}
// --------------------------
func unsafeCmpZero(ptr unsafe.Pointer, size int) bool {
// verified that size is always within right range, so no chance of OOM
var s1 = unsafeString{ptr, size}
var s2 = unsafeString{unsafeZeroAddr, size}
if size > len(unsafeZeroArr) {
arr := make([]byte, size)
s2.Data = unsafe.Pointer(&arr[0])
}
return *(*string)(unsafe.Pointer(&s1)) == *(*string)(unsafe.Pointer(&s2)) // memcmp
}
func isEmptyValue(v reflect.Value, tinfos *TypeInfos, recursive bool) bool {
urv := (*unsafeReflectValue)(unsafe.Pointer(&v))
if urv.flag == 0 {
return true
}
if recursive {
return isEmptyValueFallbackRecur(urv, v, tinfos)
}
return unsafeCmpZero(urv.ptr, int(rtsize2(urv.typ)))
}
func isEmptyValueFallbackRecur(urv *unsafeReflectValue, v reflect.Value, tinfos *TypeInfos) bool {
const recursive = true
switch v.Kind() {
case reflect.Invalid:
return true
case reflect.String:
return (*unsafeString)(urv.ptr).Len == 0
case reflect.Slice:
return (*unsafeSlice)(urv.ptr).Len == 0
case reflect.Bool:
return !*(*bool)(urv.ptr)
case reflect.Int:
return *(*int)(urv.ptr) == 0
case reflect.Int8:
return *(*int8)(urv.ptr) == 0
case reflect.Int16:
return *(*int16)(urv.ptr) == 0
case reflect.Int32:
return *(*int32)(urv.ptr) == 0
case reflect.Int64:
return *(*int64)(urv.ptr) == 0
case reflect.Uint:
return *(*uint)(urv.ptr) == 0
case reflect.Uint8:
return *(*uint8)(urv.ptr) == 0
case reflect.Uint16:
return *(*uint16)(urv.ptr) == 0
case reflect.Uint32:
return *(*uint32)(urv.ptr) == 0
case reflect.Uint64:
return *(*uint64)(urv.ptr) == 0
case reflect.Uintptr:
return *(*uintptr)(urv.ptr) == 0
case reflect.Float32:
return *(*float32)(urv.ptr) == 0
case reflect.Float64:
return *(*float64)(urv.ptr) == 0
case reflect.Complex64:
return unsafeCmpZero(urv.ptr, 8)
case reflect.Complex128:
return unsafeCmpZero(urv.ptr, 16)
case reflect.Struct:
// return isEmptyStruct(v, tinfos, recursive)
if tinfos == nil {
tinfos = defTypeInfos
}
ti := tinfos.find(uintptr(urv.typ))
if ti == nil {
ti = tinfos.load(v.Type())
}
return unsafeCmpZero(urv.ptr, int(ti.size))
case reflect.Interface, reflect.Ptr:
// isnil := urv.ptr == nil // (not sufficient, as a pointer value encodes the type)
isnil := urv.ptr == nil || *(*unsafe.Pointer)(urv.ptr) == nil
if recursive && !isnil {
return isEmptyValue(v.Elem(), tinfos, recursive)
}
return isnil
case reflect.UnsafePointer:
return urv.ptr == nil || *(*unsafe.Pointer)(urv.ptr) == nil
case reflect.Chan:
return urv.ptr == nil || len_chan(rvRefPtr(urv)) == 0
case reflect.Map:
return urv.ptr == nil || len_map(rvRefPtr(urv)) == 0
case reflect.Array:
return v.Len() == 0 ||
urv.ptr == nil ||
urv.typ == nil ||
rtsize2(urv.typ) == 0 ||
unsafeCmpZero(urv.ptr, int(rtsize2(urv.typ)))
}
return false
}
// --------------------------
type structFieldInfos struct {
c unsafe.Pointer // source
s unsafe.Pointer // sorted
length int
}
func (x *structFieldInfos) load(source, sorted []*structFieldInfo) {
s := (*unsafeSlice)(unsafe.Pointer(&sorted))
x.s = s.Data
x.length = s.Len
s = (*unsafeSlice)(unsafe.Pointer(&source))
x.c = s.Data
}
func (x *structFieldInfos) sorted() (v []*structFieldInfo) {
*(*unsafeSlice)(unsafe.Pointer(&v)) = unsafeSlice{x.s, x.length, x.length}
// s := (*unsafeSlice)(unsafe.Pointer(&v))
// s.Data = x.sorted0
// s.Len = x.length
// s.Cap = s.Len
return
}
func (x *structFieldInfos) source() (v []*structFieldInfo) {
*(*unsafeSlice)(unsafe.Pointer(&v)) = unsafeSlice{x.c, x.length, x.length}
return
}
// atomicXXX is expected to be 2 words (for symmetry with atomic.Value)
//
// Note that we do not atomically load/store length and data pointer separately,
// as this could lead to some races. Instead, we atomically load/store cappedSlice.
//
// Note: with atomic.(Load|Store)Pointer, we MUST work with an unsafe.Pointer directly.
// ----------------------
type atomicTypeInfoSlice struct {
v unsafe.Pointer // *[]rtid2ti
}
func (x *atomicTypeInfoSlice) load() (s []rtid2ti) {
x2 := atomic.LoadPointer(&x.v)
if x2 != nil {
s = *(*[]rtid2ti)(x2)
}
return
}
func (x *atomicTypeInfoSlice) store(p []rtid2ti) {
atomic.StorePointer(&x.v, unsafe.Pointer(&p))
}
// MARKER: in safe mode, atomicXXX are atomic.Value, which contains an interface{}.
// This is 2 words.
// consider padding atomicXXX here with a uintptr, so they fit into 2 words also.
// --------------------------
type atomicRtidFnSlice struct {
v unsafe.Pointer // *[]codecRtidFn
}
func (x *atomicRtidFnSlice) load() (s []codecRtidFn) {
x2 := atomic.LoadPointer(&x.v)
if x2 != nil {
s = *(*[]codecRtidFn)(x2)
}
return
}
func (x *atomicRtidFnSlice) store(p []codecRtidFn) {
atomic.StorePointer(&x.v, unsafe.Pointer(&p))
}
// --------------------------
type atomicClsErr struct {
v unsafe.Pointer // *clsErr
}
func (x *atomicClsErr) load() (e clsErr) {
x2 := (*clsErr)(atomic.LoadPointer(&x.v))
if x2 != nil {
e = *x2
}
return
}
func (x *atomicClsErr) store(p clsErr) {
atomic.StorePointer(&x.v, unsafe.Pointer(&p))
}
// --------------------------
// to create a reflect.Value for each member field of fauxUnion,
// we first create a global fauxUnion, and create reflect.Value
// for them all.
// This way, we have the flags and type in the reflect.Value.
// Then, when a reflect.Value is called, we just copy it,
// update the ptr to the fauxUnion's, and return it.
type unsafeDecNakedWrapper struct {
fauxUnion
ru, ri, rf, rl, rs, rb, rt reflect.Value // mapping to the primitives above
}
func (n *unsafeDecNakedWrapper) init() {
n.ru = rv4iptr(&n.u).Elem()
n.ri = rv4iptr(&n.i).Elem()
n.rf = rv4iptr(&n.f).Elem()
n.rl = rv4iptr(&n.l).Elem()
n.rs = rv4iptr(&n.s).Elem()
n.rt = rv4iptr(&n.t).Elem()
n.rb = rv4iptr(&n.b).Elem()
// n.rr[] = reflect.ValueOf(&n.)
}
var defUnsafeDecNakedWrapper unsafeDecNakedWrapper
func init() {
defUnsafeDecNakedWrapper.init()
}
func (n *fauxUnion) ru() (v reflect.Value) {
v = defUnsafeDecNakedWrapper.ru
((*unsafeReflectValue)(unsafe.Pointer(&v))).ptr = unsafe.Pointer(&n.u)
return
}
func (n *fauxUnion) ri() (v reflect.Value) {
v = defUnsafeDecNakedWrapper.ri
((*unsafeReflectValue)(unsafe.Pointer(&v))).ptr = unsafe.Pointer(&n.i)
return
}
func (n *fauxUnion) rf() (v reflect.Value) {
v = defUnsafeDecNakedWrapper.rf
((*unsafeReflectValue)(unsafe.Pointer(&v))).ptr = unsafe.Pointer(&n.f)
return
}
func (n *fauxUnion) rl() (v reflect.Value) {
v = defUnsafeDecNakedWrapper.rl
((*unsafeReflectValue)(unsafe.Pointer(&v))).ptr = unsafe.Pointer(&n.l)
return
}
func (n *fauxUnion) rs() (v reflect.Value) {
v = defUnsafeDecNakedWrapper.rs
((*unsafeReflectValue)(unsafe.Pointer(&v))).ptr = unsafe.Pointer(&n.s)
return
}
func (n *fauxUnion) rt() (v reflect.Value) {
v = defUnsafeDecNakedWrapper.rt
((*unsafeReflectValue)(unsafe.Pointer(&v))).ptr = unsafe.Pointer(&n.t)
return
}
func (n *fauxUnion) rb() (v reflect.Value) {
v = defUnsafeDecNakedWrapper.rb
((*unsafeReflectValue)(unsafe.Pointer(&v))).ptr = unsafe.Pointer(&n.b)
return
}
// --------------------------
func rvSetBytes(rv reflect.Value, v []byte) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
*(*[]byte)(urv.ptr) = v
}
func rvSetString(rv reflect.Value, v string) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
*(*string)(urv.ptr) = v
}
func rvSetBool(rv reflect.Value, v bool) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
*(*bool)(urv.ptr) = v
}
func rvSetTime(rv reflect.Value, v time.Time) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
*(*time.Time)(urv.ptr) = v
}
func rvSetFloat32(rv reflect.Value, v float32) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
*(*float32)(urv.ptr) = v
}
func rvSetFloat64(rv reflect.Value, v float64) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
*(*float64)(urv.ptr) = v
}
func rvSetComplex64(rv reflect.Value, v complex64) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
*(*complex64)(urv.ptr) = v
}
func rvSetComplex128(rv reflect.Value, v complex128) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
*(*complex128)(urv.ptr) = v
}
func rvSetInt(rv reflect.Value, v int) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
*(*int)(urv.ptr) = v
}
func rvSetInt8(rv reflect.Value, v int8) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
*(*int8)(urv.ptr) = v
}
func rvSetInt16(rv reflect.Value, v int16) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
*(*int16)(urv.ptr) = v
}
func rvSetInt32(rv reflect.Value, v int32) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
*(*int32)(urv.ptr) = v
}
func rvSetInt64(rv reflect.Value, v int64) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
*(*int64)(urv.ptr) = v
}
func rvSetUint(rv reflect.Value, v uint) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
*(*uint)(urv.ptr) = v
}
func rvSetUintptr(rv reflect.Value, v uintptr) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
*(*uintptr)(urv.ptr) = v
}
func rvSetUint8(rv reflect.Value, v uint8) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
*(*uint8)(urv.ptr) = v
}
func rvSetUint16(rv reflect.Value, v uint16) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
*(*uint16)(urv.ptr) = v
}
func rvSetUint32(rv reflect.Value, v uint32) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
*(*uint32)(urv.ptr) = v
}
func rvSetUint64(rv reflect.Value, v uint64) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
*(*uint64)(urv.ptr) = v
}
// ----------------
// rvSetZero is rv.Set(reflect.Zero(rv.Type()) for all kinds (including reflect.Interface).
func rvSetZero(rv reflect.Value) {
rvSetDirectZero(rv)
}
func rvSetIntf(rv reflect.Value, v reflect.Value) {
rv.Set(v)
}
// rvSetDirect is rv.Set for all kinds except reflect.Interface.
//
// Callers MUST not pass a value of kind reflect.Interface, as it may cause unexpected segfaults.
func rvSetDirect(rv reflect.Value, v reflect.Value) {
// MARKER: rv.Set for kind reflect.Interface may do a separate allocation if a scalar value.
// The book-keeping is onerous, so we just do the simple ones where a memmove is sufficient.
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
uv := (*unsafeReflectValue)(unsafe.Pointer(&v))
if uv.flag&unsafeFlagIndir == 0 {
*(*unsafe.Pointer)(urv.ptr) = uv.ptr
} else if uv.ptr == unsafeZeroAddr {
if urv.ptr != unsafeZeroAddr {
typedmemclr(urv.typ, urv.ptr)
}
} else {
typedmemmove(urv.typ, urv.ptr, uv.ptr)
}
}
// rvSetDirectZero is rv.Set(reflect.Zero(rv.Type()) for all kinds except reflect.Interface.
func rvSetDirectZero(rv reflect.Value) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
if urv.ptr != unsafeZeroAddr {
typedmemclr(urv.typ, urv.ptr)
}
}
// rvMakeSlice updates the slice to point to a new array.
// It copies data from old slice to new slice.
// It returns set=true iff it updates it, else it just returns a new slice pointing to a newly made array.
func rvMakeSlice(rv reflect.Value, ti *typeInfo, xlen, xcap int) (_ reflect.Value, set bool) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
ux := (*unsafeSlice)(urv.ptr)
t := ((*unsafeIntf)(unsafe.Pointer(&ti.elem))).ptr
s := unsafeSlice{newarray(t, xcap), xlen, xcap}
if ux.Len > 0 {
typedslicecopy(t, s, *ux)
}
*ux = s
return rv, true
}
// rvSlice returns a sub-slice of the slice given new lenth,
// without modifying passed in value.
// It is typically called when we know that SetLen(...) cannot be done.
func rvSlice(rv reflect.Value, length int) reflect.Value {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
var x []struct{}
ux := (*unsafeSlice)(unsafe.Pointer(&x))
*ux = *(*unsafeSlice)(urv.ptr)
ux.Len = length
urv.ptr = unsafe.Pointer(ux)
return rv
}
// rcGrowSlice updates the slice to point to a new array with the cap incremented, and len set to the new cap value.
// It copies data from old slice to new slice.
// It returns set=true iff it updates it, else it just returns a new slice pointing to a newly made array.
func rvGrowSlice(rv reflect.Value, ti *typeInfo, cap, incr int) (v reflect.Value, newcap int, set bool) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
ux := (*unsafeSlice)(urv.ptr)
t := ((*unsafeIntf)(unsafe.Pointer(&ti.elem))).ptr
*ux = unsafeGrowslice(t, *ux, cap, incr)
ux.Len = ux.Cap
return rv, ux.Cap, true
}
// ------------
func rvSliceIndex(rv reflect.Value, i int, ti *typeInfo) (v reflect.Value) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
uv := (*unsafeReflectValue)(unsafe.Pointer(&v))
uv.ptr = unsafe.Pointer(uintptr(((*unsafeSlice)(urv.ptr)).Data) + uintptr(int(ti.elemsize)*i))
uv.typ = ((*unsafeIntf)(unsafe.Pointer(&ti.elem))).ptr
uv.flag = uintptr(ti.elemkind) | unsafeFlagIndir | unsafeFlagAddr
return
}
func rvSliceZeroCap(t reflect.Type) (v reflect.Value) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&v))
urv.typ = ((*unsafeIntf)(unsafe.Pointer(&t))).ptr
urv.flag = uintptr(reflect.Slice) | unsafeFlagIndir
urv.ptr = unsafe.Pointer(&unsafeZeroSlice)
return
}
func rvLenSlice(rv reflect.Value) int {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
return (*unsafeSlice)(urv.ptr).Len
}
func rvCapSlice(rv reflect.Value) int {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
return (*unsafeSlice)(urv.ptr).Cap
}
func rvArrayIndex(rv reflect.Value, i int, ti *typeInfo) (v reflect.Value) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
uv := (*unsafeReflectValue)(unsafe.Pointer(&v))
uv.ptr = unsafe.Pointer(uintptr(urv.ptr) + uintptr(int(ti.elemsize)*i))
uv.typ = ((*unsafeIntf)(unsafe.Pointer(&ti.elem))).ptr
uv.flag = uintptr(ti.elemkind) | unsafeFlagIndir | unsafeFlagAddr
return
}
// if scratch is nil, then return a writable view (assuming canAddr=true)
func rvGetArrayBytes(rv reflect.Value, scratch []byte) (bs []byte) {
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
bx := (*unsafeSlice)(unsafe.Pointer(&bs))
bx.Data = urv.ptr
bx.Len = rv.Len()
bx.Cap = bx.Len
return
}
func rvGetArray4Slice(rv reflect.Value) (v reflect.Value) {
// It is possible that this slice is based off an array with a larger
// len that we want (where array len == slice cap).
// However, it is ok to create an array type that is a subset of the full
// e.g. full slice is based off a *[16]byte, but we can create a *[4]byte
// off of it. That is ok.
//
// Consequently, we use rvLenSlice, not rvCapSlice.
t := reflectArrayOf(rvLenSlice(rv), rv.Type().Elem())
// v = rvZeroAddrK(t, reflect.Array)
uv := (*unsafeReflectValue)(unsafe.Pointer(&v))
uv.flag = uintptr(reflect.Array) | unsafeFlagIndir | unsafeFlagAddr
uv.typ = ((*unsafeIntf)(unsafe.Pointer(&t))).ptr
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
uv.ptr = *(*unsafe.Pointer)(urv.ptr) // slice rv has a ptr to the slice.
return
}
func rvGetSlice4Array(rv reflect.Value, v interface{}) {
// v is a pointer to a slice to be populated
uv := (*unsafeIntf)(unsafe.Pointer(&v))
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
s := (*unsafeSlice)(uv.ptr)
s.Data = urv.ptr
s.Len = rv.Len()
s.Cap = s.Len
}
func rvCopySlice(dest, src reflect.Value, elemType reflect.Type) {
typedslicecopy((*unsafeIntf)(unsafe.Pointer(&elemType)).ptr,
*(*unsafeSlice)((*unsafeReflectValue)(unsafe.Pointer(&dest)).ptr),
*(*unsafeSlice)((*unsafeReflectValue)(unsafe.Pointer(&src)).ptr))
}
// ------------
func rvGetBool(rv reflect.Value) bool {
v := (*unsafeReflectValue)(unsafe.Pointer(&rv))
return *(*bool)(v.ptr)
}
func rvGetBytes(rv reflect.Value) []byte {
v := (*unsafeReflectValue)(unsafe.Pointer(&rv))
return *(*[]byte)(v.ptr)
}
func rvGetTime(rv reflect.Value) time.Time {
v := (*unsafeReflectValue)(unsafe.Pointer(&rv))
return *(*time.Time)(v.ptr)
}
func rvGetString(rv reflect.Value) string {
v := (*unsafeReflectValue)(unsafe.Pointer(&rv))
return *(*string)(v.ptr)
}
func rvGetFloat64(rv reflect.Value) float64 {
v := (*unsafeReflectValue)(unsafe.Pointer(&rv))
return *(*float64)(v.ptr)
}
func rvGetFloat32(rv reflect.Value) float32 {
v := (*unsafeReflectValue)(unsafe.Pointer(&rv))
return *(*float32)(v.ptr)
}
func rvGetComplex64(rv reflect.Value) complex64 {
v := (*unsafeReflectValue)(unsafe.Pointer(&rv))
return *(*complex64)(v.ptr)
}
func rvGetComplex128(rv reflect.Value) complex128 {
v := (*unsafeReflectValue)(unsafe.Pointer(&rv))
return *(*complex128)(v.ptr)
}
func rvGetInt(rv reflect.Value) int {
v := (*unsafeReflectValue)(unsafe.Pointer(&rv))
return *(*int)(v.ptr)
}
func rvGetInt8(rv reflect.Value) int8 {
v := (*unsafeReflectValue)(unsafe.Pointer(&rv))
return *(*int8)(v.ptr)
}
func rvGetInt16(rv reflect.Value) int16 {
v := (*unsafeReflectValue)(unsafe.Pointer(&rv))
return *(*int16)(v.ptr)
}
func rvGetInt32(rv reflect.Value) int32 {
v := (*unsafeReflectValue)(unsafe.Pointer(&rv))
return *(*int32)(v.ptr)
}
func rvGetInt64(rv reflect.Value) int64 {
v := (*unsafeReflectValue)(unsafe.Pointer(&rv))
return *(*int64)(v.ptr)
}
func rvGetUint(rv reflect.Value) uint {
v := (*unsafeReflectValue)(unsafe.Pointer(&rv))
return *(*uint)(v.ptr)
}
func rvGetUint8(rv reflect.Value) uint8 {
v := (*unsafeReflectValue)(unsafe.Pointer(&rv))
return *(*uint8)(v.ptr)
}
func rvGetUint16(rv reflect.Value) uint16 {
v := (*unsafeReflectValue)(unsafe.Pointer(&rv))
return *(*uint16)(v.ptr)
}
func rvGetUint32(rv reflect.Value) uint32 {
v := (*unsafeReflectValue)(unsafe.Pointer(&rv))
return *(*uint32)(v.ptr)
}
func rvGetUint64(rv reflect.Value) uint64 {
v := (*unsafeReflectValue)(unsafe.Pointer(&rv))
return *(*uint64)(v.ptr)
}
func rvGetUintptr(rv reflect.Value) uintptr {
v := (*unsafeReflectValue)(unsafe.Pointer(&rv))
return *(*uintptr)(v.ptr)
}
func rvLenMap(rv reflect.Value) int {
// maplen is not inlined, because as of go1.16beta, go:linkname's are not inlined.
// thus, faster to call rv.Len() directly.
//
// MARKER: review after https://github.com/golang/go/issues/20019 fixed.
// return rv.Len()
return len_map(rvRefPtr((*unsafeReflectValue)(unsafe.Pointer(&rv))))
}
// copy is an intrinsic, which may use asm if length is small,
// or make a runtime call to runtime.memmove if length is large.
// Performance suffers when you always call runtime.memmove function.
//
// Consequently, there's no value in a copybytes call - just call copy() directly
// func copybytes(to, from []byte) (n int) {
// n = (*unsafeSlice)(unsafe.Pointer(&from)).Len
// memmove(
// (*unsafeSlice)(unsafe.Pointer(&to)).Data,
// (*unsafeSlice)(unsafe.Pointer(&from)).Data,
// uintptr(n),
// )
// return
// }
// func copybytestr(to []byte, from string) (n int) {
// n = (*unsafeSlice)(unsafe.Pointer(&from)).Len
// memmove(
// (*unsafeSlice)(unsafe.Pointer(&to)).Data,
// (*unsafeSlice)(unsafe.Pointer(&from)).Data,
// uintptr(n),
// )
// return
// }
// Note: it is hard to find len(...) of an array type,
// as that is a field in the arrayType representing the array, and hard to introspect.
//
// func rvLenArray(rv reflect.Value) int { return rv.Len() }
// ------------ map range and map indexing ----------
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | true |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ugorji/go/codec/goversion_vendor_gte_go17.go | vendor/github.com/ugorji/go/codec/goversion_vendor_gte_go17.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
//go:build go1.7
// +build go1.7
package codec
const genCheckVendor = 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/ugorji/go/codec/codecgen.go | vendor/github.com/ugorji/go/codec/codecgen.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
//go:build codecgen || generated
// +build codecgen generated
package codec
// this file sets the codecgen variable to true
// when the build tag codecgen is set.
//
// some tests depend on knowing whether in the context of codecgen or not.
// For example, some tests should be skipped during codecgen e.g. missing fields tests.
func init() {
codecgen = 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/ugorji/go/codec/encode.go | vendor/github.com/ugorji/go/codec/encode.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
package codec
import (
"encoding"
"errors"
"io"
"reflect"
"sort"
"strconv"
"time"
)
// defEncByteBufSize is the default size of []byte used
// for bufio buffer or []byte (when nil passed)
const defEncByteBufSize = 1 << 10 // 4:16, 6:64, 8:256, 10:1024
var errEncoderNotInitialized = errors.New("Encoder not initialized")
// encDriver abstracts the actual codec (binc vs msgpack, etc)
type encDriver interface {
EncodeNil()
EncodeInt(i int64)
EncodeUint(i uint64)
EncodeBool(b bool)
EncodeFloat32(f float32)
EncodeFloat64(f float64)
EncodeRawExt(re *RawExt)
EncodeExt(v interface{}, basetype reflect.Type, xtag uint64, ext Ext)
// EncodeString using cUTF8, honor'ing StringToRaw flag
EncodeString(v string)
EncodeStringBytesRaw(v []byte)
EncodeTime(time.Time)
WriteArrayStart(length int)
WriteArrayEnd()
WriteMapStart(length int)
WriteMapEnd()
// reset will reset current encoding runtime state, and cached information from the handle
reset()
encoder() *Encoder
driverStateManager
}
type encDriverContainerTracker interface {
WriteArrayElem()
WriteMapElemKey()
WriteMapElemValue()
}
type encDriverNoState struct{}
func (encDriverNoState) captureState() interface{} { return nil }
func (encDriverNoState) reset() {}
func (encDriverNoState) resetState() {}
func (encDriverNoState) restoreState(v interface{}) {}
type encDriverNoopContainerWriter struct{}
func (encDriverNoopContainerWriter) WriteArrayStart(length int) {}
func (encDriverNoopContainerWriter) WriteArrayEnd() {}
func (encDriverNoopContainerWriter) WriteMapStart(length int) {}
func (encDriverNoopContainerWriter) WriteMapEnd() {}
// encStructFieldObj[Slice] is used for sorting when there are missing fields and canonical flag is set
type encStructFieldObj struct {
key string
rv reflect.Value
intf interface{}
ascii bool
isRv bool
}
type encStructFieldObjSlice []encStructFieldObj
func (p encStructFieldObjSlice) Len() int { return len(p) }
func (p encStructFieldObjSlice) Swap(i, j int) { p[uint(i)], p[uint(j)] = p[uint(j)], p[uint(i)] }
func (p encStructFieldObjSlice) Less(i, j int) bool {
return p[uint(i)].key < p[uint(j)].key
}
// EncodeOptions captures configuration options during encode.
type EncodeOptions struct {
// WriterBufferSize is the size of the buffer used when writing.
//
// if > 0, we use a smart buffer internally for performance purposes.
WriterBufferSize int
// ChanRecvTimeout is the timeout used when selecting from a chan.
//
// Configuring this controls how we receive from a chan during the encoding process.
// - If ==0, we only consume the elements currently available in the chan.
// - if <0, we consume until the chan is closed.
// - If >0, we consume until this timeout.
ChanRecvTimeout time.Duration
// StructToArray specifies to encode a struct as an array, and not as a map
StructToArray bool
// Canonical representation means that encoding a value will always result in the same
// sequence of bytes.
//
// This only affects maps, as the iteration order for maps is random.
//
// The implementation MAY use the natural sort order for the map keys if possible:
//
// - If there is a natural sort order (ie for number, bool, string or []byte keys),
// then the map keys are first sorted in natural order and then written
// with corresponding map values to the strema.
// - If there is no natural sort order, then the map keys will first be
// encoded into []byte, and then sorted,
// before writing the sorted keys and the corresponding map values to the stream.
//
Canonical bool
// CheckCircularRef controls whether we check for circular references
// and error fast during an encode.
//
// If enabled, an error is received if a pointer to a struct
// references itself either directly or through one of its fields (iteratively).
//
// This is opt-in, as there may be a performance hit to checking circular references.
CheckCircularRef bool
// RecursiveEmptyCheck controls how we determine whether a value is empty.
//
// If true, we descend into interfaces and pointers to reursively check if value is empty.
//
// We *might* check struct fields one by one to see if empty
// (if we cannot directly check if a struct value is equal to its zero value).
// If so, we honor IsZero, Comparable, IsCodecEmpty(), etc.
// Note: This *may* make OmitEmpty more expensive due to the large number of reflect calls.
//
// If false, we check if the value is equal to its zero value (newly allocated state).
RecursiveEmptyCheck bool
// Raw controls whether we encode Raw values.
// This is a "dangerous" option and must be explicitly set.
// If set, we blindly encode Raw values as-is, without checking
// if they are a correct representation of a value in that format.
// If unset, we error out.
Raw bool
// StringToRaw controls how strings are encoded.
//
// As a go string is just an (immutable) sequence of bytes,
// it can be encoded either as raw bytes or as a UTF string.
//
// By default, strings are encoded as UTF-8.
// but can be treated as []byte during an encode.
//
// Note that things which we know (by definition) to be UTF-8
// are ALWAYS encoded as UTF-8 strings.
// These include encoding.TextMarshaler, time.Format calls, struct field names, etc.
StringToRaw bool
// OptimumSize controls whether we optimize for the smallest size.
//
// Some formats will use this flag to determine whether to encode
// in the smallest size possible, even if it takes slightly longer.
//
// For example, some formats that support half-floats might check if it is possible
// to store a float64 as a half float. Doing this check has a small performance cost,
// but the benefit is that the encoded message will be smaller.
OptimumSize bool
// NoAddressableReadonly controls whether we try to force a non-addressable value
// to be addressable so we can call a pointer method on it e.g. for types
// that support Selfer, json.Marshaler, etc.
//
// Use it in the very rare occurrence that your types modify a pointer value when calling
// an encode callback function e.g. JsonMarshal, TextMarshal, BinaryMarshal or CodecEncodeSelf.
NoAddressableReadonly bool
}
// ---------------------------------------------
func (e *Encoder) rawExt(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeRawExt(rv2i(rv).(*RawExt))
}
func (e *Encoder) ext(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeExt(rv2i(rv), f.ti.rt, f.xfTag, f.xfFn)
}
func (e *Encoder) selferMarshal(f *codecFnInfo, rv reflect.Value) {
rv2i(rv).(Selfer).CodecEncodeSelf(e)
}
func (e *Encoder) binaryMarshal(f *codecFnInfo, rv reflect.Value) {
bs, fnerr := rv2i(rv).(encoding.BinaryMarshaler).MarshalBinary()
e.marshalRaw(bs, fnerr)
}
func (e *Encoder) textMarshal(f *codecFnInfo, rv reflect.Value) {
bs, fnerr := rv2i(rv).(encoding.TextMarshaler).MarshalText()
e.marshalUtf8(bs, fnerr)
}
func (e *Encoder) jsonMarshal(f *codecFnInfo, rv reflect.Value) {
bs, fnerr := rv2i(rv).(jsonMarshaler).MarshalJSON()
e.marshalAsis(bs, fnerr)
}
func (e *Encoder) raw(f *codecFnInfo, rv reflect.Value) {
e.rawBytes(rv2i(rv).(Raw))
}
func (e *Encoder) encodeComplex64(v complex64) {
if imag(v) != 0 {
e.errorf("cannot encode complex number: %v, with imaginary values: %v", v, imag(v))
}
e.e.EncodeFloat32(real(v))
}
func (e *Encoder) encodeComplex128(v complex128) {
if imag(v) != 0 {
e.errorf("cannot encode complex number: %v, with imaginary values: %v", v, imag(v))
}
e.e.EncodeFloat64(real(v))
}
func (e *Encoder) kBool(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeBool(rvGetBool(rv))
}
func (e *Encoder) kTime(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeTime(rvGetTime(rv))
}
func (e *Encoder) kString(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeString(rvGetString(rv))
}
func (e *Encoder) kFloat32(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeFloat32(rvGetFloat32(rv))
}
func (e *Encoder) kFloat64(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeFloat64(rvGetFloat64(rv))
}
func (e *Encoder) kComplex64(f *codecFnInfo, rv reflect.Value) {
e.encodeComplex64(rvGetComplex64(rv))
}
func (e *Encoder) kComplex128(f *codecFnInfo, rv reflect.Value) {
e.encodeComplex128(rvGetComplex128(rv))
}
func (e *Encoder) kInt(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeInt(int64(rvGetInt(rv)))
}
func (e *Encoder) kInt8(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeInt(int64(rvGetInt8(rv)))
}
func (e *Encoder) kInt16(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeInt(int64(rvGetInt16(rv)))
}
func (e *Encoder) kInt32(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeInt(int64(rvGetInt32(rv)))
}
func (e *Encoder) kInt64(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeInt(int64(rvGetInt64(rv)))
}
func (e *Encoder) kUint(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeUint(uint64(rvGetUint(rv)))
}
func (e *Encoder) kUint8(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeUint(uint64(rvGetUint8(rv)))
}
func (e *Encoder) kUint16(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeUint(uint64(rvGetUint16(rv)))
}
func (e *Encoder) kUint32(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeUint(uint64(rvGetUint32(rv)))
}
func (e *Encoder) kUint64(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeUint(uint64(rvGetUint64(rv)))
}
func (e *Encoder) kUintptr(f *codecFnInfo, rv reflect.Value) {
e.e.EncodeUint(uint64(rvGetUintptr(rv)))
}
func (e *Encoder) kErr(f *codecFnInfo, rv reflect.Value) {
e.errorf("unsupported kind %s, for %#v", rv.Kind(), rv)
}
func chanToSlice(rv reflect.Value, rtslice reflect.Type, timeout time.Duration) (rvcs reflect.Value) {
rvcs = rvZeroK(rtslice, reflect.Slice)
if timeout < 0 { // consume until close
for {
recv, recvOk := rv.Recv()
if !recvOk {
break
}
rvcs = reflect.Append(rvcs, recv)
}
} else {
cases := make([]reflect.SelectCase, 2)
cases[0] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: rv}
if timeout == 0 {
cases[1] = reflect.SelectCase{Dir: reflect.SelectDefault}
} else {
tt := time.NewTimer(timeout)
cases[1] = reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(tt.C)}
}
for {
chosen, recv, recvOk := reflect.Select(cases)
if chosen == 1 || !recvOk {
break
}
rvcs = reflect.Append(rvcs, recv)
}
}
return
}
func (e *Encoder) kSeqFn(rtelem reflect.Type) (fn *codecFn) {
for rtelem.Kind() == reflect.Ptr {
rtelem = rtelem.Elem()
}
// if kind is reflect.Interface, do not pre-determine the encoding type,
// because preEncodeValue may break it down to a concrete type and kInterface will bomb.
if rtelem.Kind() != reflect.Interface {
fn = e.h.fn(rtelem)
}
return
}
func (e *Encoder) kSliceWMbs(rv reflect.Value, ti *typeInfo) {
var l = rvLenSlice(rv)
if l == 0 {
e.mapStart(0)
} else {
e.haltOnMbsOddLen(l)
e.mapStart(l >> 1) // e.mapStart(l / 2)
fn := e.kSeqFn(ti.elem)
for j := 0; j < l; j++ {
if j&1 == 0 { // j%2 == 0 {
e.mapElemKey()
} else {
e.mapElemValue()
}
e.encodeValue(rvSliceIndex(rv, j, ti), fn)
}
}
e.mapEnd()
}
func (e *Encoder) kSliceW(rv reflect.Value, ti *typeInfo) {
var l = rvLenSlice(rv)
e.arrayStart(l)
if l > 0 {
fn := e.kSeqFn(ti.elem)
for j := 0; j < l; j++ {
e.arrayElem()
e.encodeValue(rvSliceIndex(rv, j, ti), fn)
}
}
e.arrayEnd()
}
func (e *Encoder) kArrayWMbs(rv reflect.Value, ti *typeInfo) {
var l = rv.Len()
if l == 0 {
e.mapStart(0)
} else {
e.haltOnMbsOddLen(l)
e.mapStart(l >> 1) // e.mapStart(l / 2)
fn := e.kSeqFn(ti.elem)
for j := 0; j < l; j++ {
if j&1 == 0 { // j%2 == 0 {
e.mapElemKey()
} else {
e.mapElemValue()
}
e.encodeValue(rv.Index(j), fn)
}
}
e.mapEnd()
}
func (e *Encoder) kArrayW(rv reflect.Value, ti *typeInfo) {
var l = rv.Len()
e.arrayStart(l)
if l > 0 {
fn := e.kSeqFn(ti.elem)
for j := 0; j < l; j++ {
e.arrayElem()
e.encodeValue(rv.Index(j), fn)
}
}
e.arrayEnd()
}
func (e *Encoder) kChan(f *codecFnInfo, rv reflect.Value) {
if f.ti.chandir&uint8(reflect.RecvDir) == 0 {
e.errorf("send-only channel cannot be encoded")
}
if !f.ti.mbs && uint8TypId == rt2id(f.ti.elem) {
e.kSliceBytesChan(rv)
return
}
rtslice := reflect.SliceOf(f.ti.elem)
rv = chanToSlice(rv, rtslice, e.h.ChanRecvTimeout)
ti := e.h.getTypeInfo(rt2id(rtslice), rtslice)
if f.ti.mbs {
e.kSliceWMbs(rv, ti)
} else {
e.kSliceW(rv, ti)
}
}
func (e *Encoder) kSlice(f *codecFnInfo, rv reflect.Value) {
if f.ti.mbs {
e.kSliceWMbs(rv, f.ti)
} else if f.ti.rtid == uint8SliceTypId || uint8TypId == rt2id(f.ti.elem) {
e.e.EncodeStringBytesRaw(rvGetBytes(rv))
} else {
e.kSliceW(rv, f.ti)
}
}
func (e *Encoder) kArray(f *codecFnInfo, rv reflect.Value) {
if f.ti.mbs {
e.kArrayWMbs(rv, f.ti)
} else if handleBytesWithinKArray && uint8TypId == rt2id(f.ti.elem) {
e.e.EncodeStringBytesRaw(rvGetArrayBytes(rv, []byte{}))
} else {
e.kArrayW(rv, f.ti)
}
}
func (e *Encoder) kSliceBytesChan(rv reflect.Value) {
// do not use range, so that the number of elements encoded
// does not change, and encoding does not hang waiting on someone to close chan.
bs0 := e.blist.peek(32, true)
bs := bs0
irv := rv2i(rv)
ch, ok := irv.(<-chan byte)
if !ok {
ch = irv.(chan byte)
}
L1:
switch timeout := e.h.ChanRecvTimeout; {
case timeout == 0: // only consume available
for {
select {
case b := <-ch:
bs = append(bs, b)
default:
break L1
}
}
case timeout > 0: // consume until timeout
tt := time.NewTimer(timeout)
for {
select {
case b := <-ch:
bs = append(bs, b)
case <-tt.C:
// close(tt.C)
break L1
}
}
default: // consume until close
for b := range ch {
bs = append(bs, b)
}
}
e.e.EncodeStringBytesRaw(bs)
e.blist.put(bs)
if !byteSliceSameData(bs0, bs) {
e.blist.put(bs0)
}
}
func (e *Encoder) kStructSfi(f *codecFnInfo) []*structFieldInfo {
if e.h.Canonical {
return f.ti.sfi.sorted()
}
return f.ti.sfi.source()
}
func (e *Encoder) kStructNoOmitempty(f *codecFnInfo, rv reflect.Value) {
var tisfi []*structFieldInfo
if f.ti.toArray || e.h.StructToArray { // toArray
tisfi = f.ti.sfi.source()
e.arrayStart(len(tisfi))
for _, si := range tisfi {
e.arrayElem()
e.encodeValue(si.path.field(rv), nil)
}
e.arrayEnd()
} else {
tisfi = e.kStructSfi(f)
e.mapStart(len(tisfi))
keytyp := f.ti.keyType
for _, si := range tisfi {
e.mapElemKey()
e.kStructFieldKey(keytyp, si.path.encNameAsciiAlphaNum, si.encName)
e.mapElemValue()
e.encodeValue(si.path.field(rv), nil)
}
e.mapEnd()
}
}
func (e *Encoder) kStructFieldKey(keyType valueType, encNameAsciiAlphaNum bool, encName string) {
encStructFieldKey(encName, e.e, e.w(), keyType, encNameAsciiAlphaNum, e.js)
}
func (e *Encoder) kStruct(f *codecFnInfo, rv reflect.Value) {
var newlen int
ti := f.ti
toMap := !(ti.toArray || e.h.StructToArray)
var mf map[string]interface{}
if ti.flagMissingFielder {
mf = rv2i(rv).(MissingFielder).CodecMissingFields()
toMap = true
newlen += len(mf)
} else if ti.flagMissingFielderPtr {
rv2 := e.addrRV(rv, ti.rt, ti.ptr)
mf = rv2i(rv2).(MissingFielder).CodecMissingFields()
toMap = true
newlen += len(mf)
}
tisfi := ti.sfi.source()
newlen += len(tisfi)
var fkvs = e.slist.get(newlen)[:newlen]
recur := e.h.RecursiveEmptyCheck
var kv sfiRv
var j int
if toMap {
newlen = 0
for _, si := range e.kStructSfi(f) {
kv.r = si.path.field(rv)
if si.path.omitEmpty && isEmptyValue(kv.r, e.h.TypeInfos, recur) {
continue
}
kv.v = si
fkvs[newlen] = kv
newlen++
}
var mf2s []stringIntf
if len(mf) > 0 {
mf2s = make([]stringIntf, 0, len(mf))
for k, v := range mf {
if k == "" {
continue
}
if ti.infoFieldOmitempty && isEmptyValue(reflect.ValueOf(v), e.h.TypeInfos, recur) {
continue
}
mf2s = append(mf2s, stringIntf{k, v})
}
}
e.mapStart(newlen + len(mf2s))
// When there are missing fields, and Canonical flag is set,
// we cannot have the missing fields and struct fields sorted independently.
// We have to capture them together and sort as a unit.
if len(mf2s) > 0 && e.h.Canonical {
mf2w := make([]encStructFieldObj, newlen+len(mf2s))
for j = 0; j < newlen; j++ {
kv = fkvs[j]
mf2w[j] = encStructFieldObj{kv.v.encName, kv.r, nil, kv.v.path.encNameAsciiAlphaNum, true}
}
for _, v := range mf2s {
mf2w[j] = encStructFieldObj{v.v, reflect.Value{}, v.i, false, false}
j++
}
sort.Sort((encStructFieldObjSlice)(mf2w))
for _, v := range mf2w {
e.mapElemKey()
e.kStructFieldKey(ti.keyType, v.ascii, v.key)
e.mapElemValue()
if v.isRv {
e.encodeValue(v.rv, nil)
} else {
e.encode(v.intf)
}
}
} else {
keytyp := ti.keyType
for j = 0; j < newlen; j++ {
kv = fkvs[j]
e.mapElemKey()
e.kStructFieldKey(keytyp, kv.v.path.encNameAsciiAlphaNum, kv.v.encName)
e.mapElemValue()
e.encodeValue(kv.r, nil)
}
for _, v := range mf2s {
e.mapElemKey()
e.kStructFieldKey(keytyp, false, v.v)
e.mapElemValue()
e.encode(v.i)
}
}
e.mapEnd()
} else {
newlen = len(tisfi)
for i, si := range tisfi { // use unsorted array (to match sequence in struct)
kv.r = si.path.field(rv)
// use the zero value.
// if a reference or struct, set to nil (so you do not output too much)
if si.path.omitEmpty && isEmptyValue(kv.r, e.h.TypeInfos, recur) {
switch kv.r.Kind() {
case reflect.Struct, reflect.Interface, reflect.Ptr, reflect.Array, reflect.Map, reflect.Slice:
kv.r = reflect.Value{} //encode as nil
}
}
fkvs[i] = kv
}
// encode it all
e.arrayStart(newlen)
for j = 0; j < newlen; j++ {
e.arrayElem()
e.encodeValue(fkvs[j].r, nil)
}
e.arrayEnd()
}
// do not use defer. Instead, use explicit pool return at end of function.
// defer has a cost we are trying to avoid.
// If there is a panic and these slices are not returned, it is ok.
e.slist.put(fkvs)
}
func (e *Encoder) kMap(f *codecFnInfo, rv reflect.Value) {
l := rvLenMap(rv)
e.mapStart(l)
if l == 0 {
e.mapEnd()
return
}
// determine the underlying key and val encFn's for the map.
// This eliminates some work which is done for each loop iteration i.e.
// rv.Type(), ref.ValueOf(rt).Pointer(), then check map/list for fn.
//
// However, if kind is reflect.Interface, do not pre-determine the
// encoding type, because preEncodeValue may break it down to
// a concrete type and kInterface will bomb.
var keyFn, valFn *codecFn
ktypeKind := reflect.Kind(f.ti.keykind)
vtypeKind := reflect.Kind(f.ti.elemkind)
rtval := f.ti.elem
rtvalkind := vtypeKind
for rtvalkind == reflect.Ptr {
rtval = rtval.Elem()
rtvalkind = rtval.Kind()
}
if rtvalkind != reflect.Interface {
valFn = e.h.fn(rtval)
}
var rvv = mapAddrLoopvarRV(f.ti.elem, vtypeKind)
rtkey := f.ti.key
var keyTypeIsString = stringTypId == rt2id(rtkey) // rtkeyid
if keyTypeIsString {
keyFn = e.h.fn(rtkey)
} else {
for rtkey.Kind() == reflect.Ptr {
rtkey = rtkey.Elem()
}
if rtkey.Kind() != reflect.Interface {
keyFn = e.h.fn(rtkey)
}
}
if e.h.Canonical {
e.kMapCanonical(f.ti, rv, rvv, keyFn, valFn)
e.mapEnd()
return
}
var rvk = mapAddrLoopvarRV(f.ti.key, ktypeKind)
var it mapIter
mapRange(&it, rv, rvk, rvv, true)
for it.Next() {
e.mapElemKey()
if keyTypeIsString {
e.e.EncodeString(it.Key().String())
} else {
e.encodeValue(it.Key(), keyFn)
}
e.mapElemValue()
e.encodeValue(it.Value(), valFn)
}
it.Done()
e.mapEnd()
}
func (e *Encoder) kMapCanonical(ti *typeInfo, rv, rvv reflect.Value, keyFn, valFn *codecFn) {
// The base kind of the type of the map key is sufficient for ordering.
// We only do out of band if that kind is not ordered (number or string), bool or time.Time.
// If the key is a predeclared type, directly call methods on encDriver e.g. EncodeString
// but if not, call encodeValue, in case it has an extension registered or otherwise.
rtkey := ti.key
rtkeydecl := rtkey.PkgPath() == "" && rtkey.Name() != "" // key type is predeclared
mks := rv.MapKeys()
rtkeyKind := rtkey.Kind()
kfast := mapKeyFastKindFor(rtkeyKind)
visindirect := mapStoresElemIndirect(uintptr(ti.elemsize))
visref := refBitset.isset(ti.elemkind)
switch rtkeyKind {
case reflect.Bool:
// though bool keys make no sense in a map, it *could* happen.
// in that case, we MUST support it in reflection mode,
// as that is the fallback for even codecgen and others.
// sort the keys so that false comes before true
// ie if 2 keys in order (true, false), then swap them
if len(mks) == 2 && mks[0].Bool() {
mks[0], mks[1] = mks[1], mks[0]
}
for i := range mks {
e.mapElemKey()
if rtkeydecl {
e.e.EncodeBool(mks[i].Bool())
} else {
e.encodeValueNonNil(mks[i], keyFn)
}
e.mapElemValue()
e.encodeValue(mapGet(rv, mks[i], rvv, kfast, visindirect, visref), valFn)
}
case reflect.String:
mksv := make([]stringRv, len(mks))
for i, k := range mks {
v := &mksv[i]
v.r = k
v.v = k.String()
}
sort.Sort(stringRvSlice(mksv))
for i := range mksv {
e.mapElemKey()
if rtkeydecl {
e.e.EncodeString(mksv[i].v)
} else {
e.encodeValueNonNil(mksv[i].r, keyFn)
}
e.mapElemValue()
e.encodeValue(mapGet(rv, mksv[i].r, rvv, kfast, visindirect, visref), valFn)
}
case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint, reflect.Uintptr:
mksv := make([]uint64Rv, len(mks))
for i, k := range mks {
v := &mksv[i]
v.r = k
v.v = k.Uint()
}
sort.Sort(uint64RvSlice(mksv))
for i := range mksv {
e.mapElemKey()
if rtkeydecl {
e.e.EncodeUint(mksv[i].v)
} else {
e.encodeValueNonNil(mksv[i].r, keyFn)
}
e.mapElemValue()
e.encodeValue(mapGet(rv, mksv[i].r, rvv, kfast, visindirect, visref), valFn)
}
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
mksv := make([]int64Rv, len(mks))
for i, k := range mks {
v := &mksv[i]
v.r = k
v.v = k.Int()
}
sort.Sort(int64RvSlice(mksv))
for i := range mksv {
e.mapElemKey()
if rtkeydecl {
e.e.EncodeInt(mksv[i].v)
} else {
e.encodeValueNonNil(mksv[i].r, keyFn)
}
e.mapElemValue()
e.encodeValue(mapGet(rv, mksv[i].r, rvv, kfast, visindirect, visref), valFn)
}
case reflect.Float32:
mksv := make([]float64Rv, len(mks))
for i, k := range mks {
v := &mksv[i]
v.r = k
v.v = k.Float()
}
sort.Sort(float64RvSlice(mksv))
for i := range mksv {
e.mapElemKey()
if rtkeydecl {
e.e.EncodeFloat32(float32(mksv[i].v))
} else {
e.encodeValueNonNil(mksv[i].r, keyFn)
}
e.mapElemValue()
e.encodeValue(mapGet(rv, mksv[i].r, rvv, kfast, visindirect, visref), valFn)
}
case reflect.Float64:
mksv := make([]float64Rv, len(mks))
for i, k := range mks {
v := &mksv[i]
v.r = k
v.v = k.Float()
}
sort.Sort(float64RvSlice(mksv))
for i := range mksv {
e.mapElemKey()
if rtkeydecl {
e.e.EncodeFloat64(mksv[i].v)
} else {
e.encodeValueNonNil(mksv[i].r, keyFn)
}
e.mapElemValue()
e.encodeValue(mapGet(rv, mksv[i].r, rvv, kfast, visindirect, visref), valFn)
}
default:
if rtkey == timeTyp {
mksv := make([]timeRv, len(mks))
for i, k := range mks {
v := &mksv[i]
v.r = k
v.v = rv2i(k).(time.Time)
}
sort.Sort(timeRvSlice(mksv))
for i := range mksv {
e.mapElemKey()
e.e.EncodeTime(mksv[i].v)
e.mapElemValue()
e.encodeValue(mapGet(rv, mksv[i].r, rvv, kfast, visindirect, visref), valFn)
}
break
}
// out-of-band
// first encode each key to a []byte first, then sort them, then record
bs0 := e.blist.get(len(mks) * 16)
mksv := bs0
mksbv := make([]bytesRv, len(mks))
func() {
// replicate sideEncode logic
defer func(wb bytesEncAppender, bytes bool, c containerState, state interface{}) {
e.wb = wb
e.bytes = bytes
e.c = c
e.e.restoreState(state)
}(e.wb, e.bytes, e.c, e.e.captureState())
// e2 := NewEncoderBytes(&mksv, e.hh)
e.wb = bytesEncAppender{mksv[:0], &mksv}
e.bytes = true
e.c = 0
e.e.resetState()
for i, k := range mks {
v := &mksbv[i]
l := len(mksv)
e.c = containerMapKey
e.encodeValue(k, nil)
e.atEndOfEncode()
e.w().end()
v.r = k
v.v = mksv[l:]
}
}()
sort.Sort(bytesRvSlice(mksbv))
for j := range mksbv {
e.mapElemKey()
e.encWr.writeb(mksbv[j].v)
e.mapElemValue()
e.encodeValue(mapGet(rv, mksbv[j].r, rvv, kfast, visindirect, visref), valFn)
}
e.blist.put(mksv)
if !byteSliceSameData(bs0, mksv) {
e.blist.put(bs0)
}
}
}
// Encoder writes an object to an output stream in a supported format.
//
// Encoder is NOT safe for concurrent use i.e. a Encoder cannot be used
// concurrently in multiple goroutines.
//
// However, as Encoder could be allocation heavy to initialize, a Reset method is provided
// so its state can be reused to decode new input streams repeatedly.
// This is the idiomatic way to use.
type Encoder struct {
panicHdl
e encDriver
h *BasicHandle
// hopefully, reduce derefencing cost by laying the encWriter inside the Encoder
encWr
// ---- cpu cache line boundary
hh Handle
blist bytesFreelist
err error
// ---- cpu cache line boundary
// ---- writable fields during execution --- *try* to keep in sep cache line
// ci holds interfaces during an encoding (if CheckCircularRef=true)
//
// We considered using a []uintptr (slice of pointer addresses) retrievable via rv.UnsafeAddr.
// However, it is possible for the same pointer to point to 2 different types e.g.
// type T struct { tHelper }
// Here, for var v T; &v and &v.tHelper are the same pointer.
// Consequently, we need a tuple of type and pointer, which interface{} natively provides.
ci []interface{} // []uintptr
perType encPerType
slist sfiRvFreelist
}
// NewEncoder returns an Encoder for encoding into an io.Writer.
//
// For efficiency, Users are encouraged to configure WriterBufferSize on the handle
// OR pass in a memory buffered writer (eg bufio.Writer, bytes.Buffer).
func NewEncoder(w io.Writer, h Handle) *Encoder {
e := h.newEncDriver().encoder()
if w != nil {
e.Reset(w)
}
return e
}
// NewEncoderBytes returns an encoder for encoding directly and efficiently
// into a byte slice, using zero-copying to temporary slices.
//
// It will potentially replace the output byte slice pointed to.
// After encoding, the out parameter contains the encoded contents.
func NewEncoderBytes(out *[]byte, h Handle) *Encoder {
e := h.newEncDriver().encoder()
if out != nil {
e.ResetBytes(out)
}
return e
}
func (e *Encoder) HandleName() string {
return e.hh.Name()
}
func (e *Encoder) init(h Handle) {
initHandle(h)
e.err = errEncoderNotInitialized
e.bytes = true
e.hh = h
e.h = h.getBasicHandle()
e.be = e.hh.isBinary()
}
func (e *Encoder) w() *encWr {
return &e.encWr
}
func (e *Encoder) resetCommon() {
e.e.reset()
if e.ci != nil {
e.ci = e.ci[:0]
}
e.c = 0
e.calls = 0
e.seq = 0
e.err = nil
}
// Reset resets the Encoder with a new output stream.
//
// This accommodates using the state of the Encoder,
// where it has "cached" information about sub-engines.
func (e *Encoder) Reset(w io.Writer) {
e.bytes = false
if e.wf == nil {
e.wf = new(bufioEncWriter)
}
e.wf.reset(w, e.h.WriterBufferSize, &e.blist)
e.resetCommon()
}
// ResetBytes resets the Encoder with a new destination output []byte.
func (e *Encoder) ResetBytes(out *[]byte) {
e.bytes = true
e.wb.reset(encInBytes(out), out)
e.resetCommon()
}
// Encode writes an object into a stream.
//
// Encoding can be configured via the struct tag for the fields.
// The key (in the struct tags) that we look at is configurable.
//
// By default, we look up the "codec" key in the struct field's tags,
// and fall bak to the "json" key if "codec" is absent.
// That key in struct field's tag value is the key name,
// followed by an optional comma and options.
//
// To set an option on all fields (e.g. omitempty on all fields), you
// can create a field called _struct, and set flags on it. The options
// which can be set on _struct are:
// - omitempty: so all fields are omitted if empty
// - toarray: so struct is encoded as an array
// - int: so struct key names are encoded as signed integers (instead of strings)
// - uint: so struct key names are encoded as unsigned integers (instead of strings)
// - float: so struct key names are encoded as floats (instead of strings)
//
// More details on these below.
//
// Struct values "usually" encode as maps. Each exported struct field is encoded unless:
// - the field's tag is "-", OR
// - the field is empty (empty or the zero value) and its tag specifies the "omitempty" option.
//
// When encoding as a map, the first string in the tag (before the comma)
// is the map key string to use when encoding.
// ...
// This key is typically encoded as a string.
// However, there are instances where the encoded stream has mapping keys encoded as numbers.
// For example, some cbor streams have keys as integer codes in the stream, but they should map
// to fields in a structured object. Consequently, a struct is the natural representation in code.
// For these, configure the struct to encode/decode the keys as numbers (instead of string).
// This is done with the int,uint or float option on the _struct field (see above).
//
// However, struct values may encode as arrays. This happens when:
// - StructToArray Encode option is set, OR
// - the tag on the _struct field sets the "toarray" option
//
// Note that omitempty is ignored when encoding struct values as arrays,
// as an entry must be encoded for each field, to maintain its position.
//
// Values with types that implement MapBySlice are encoded as stream maps.
//
// The empty values (for omitempty option) are false, 0, any nil pointer
// or interface value, and any array, slice, map, or string of length zero.
//
// Anonymous fields are encoded inline except:
// - the struct tag specifies a replacement name (first value)
// - the field is of an interface type
//
// Examples:
//
// // NOTE: 'json:' can be used as struct tag key, in place 'codec:' below.
// type MyStruct struct {
// _struct bool `codec:",omitempty"` //set omitempty for every field
// Field1 string `codec:"-"` //skip this field
// Field2 int `codec:"myName"` //Use key "myName" in encode stream
// Field3 int32 `codec:",omitempty"` //use key "Field3". Omit if empty.
// Field4 bool `codec:"f4,omitempty"` //use key "f4". Omit if empty.
// io.Reader //use key "Reader".
// MyStruct `codec:"my1" //use key "my1".
// MyStruct //inline it
// ...
// }
//
// type MyStruct struct {
// _struct bool `codec:",toarray"` //encode struct as an array
// }
//
// type MyStruct struct {
// _struct bool `codec:",uint"` //encode struct with "unsigned integer" keys
// Field1 string `codec:"1"` //encode Field1 key using: EncodeInt(1)
// Field2 string `codec:"2"` //encode Field2 key using: EncodeInt(2)
// }
//
// The mode of encoding is based on the type of the value. When a value is seen:
// - If a Selfer, call its CodecEncodeSelf method
// - If an extension is registered for it, call that extension function
// - If implements encoding.(Binary|Text|JSON)Marshaler, call Marshal(Binary|Text|JSON) method
// - Else encode it based on its reflect.Kind
//
// Note that struct field names and keys in map[string]XXX will be treated as symbols.
// Some formats support symbols (e.g. binc) and will properly encode the string
// only once in the stream, and use a tag to refer to it thereafter.
func (e *Encoder) Encode(v interface{}) (err error) {
// tried to use closure, as runtime optimizes defer with no params.
// This seemed to be causing weird issues (like circular reference found, unexpected panic, etc).
// Also, see https://github.com/golang/go/issues/14939#issuecomment-417836139
if !debugging {
defer func() {
// if error occurred during encoding, return that error;
// else if error occurred on end'ing (i.e. during flush), return that error.
if x := recover(); x != nil {
panicValToErr(e, x, &e.err)
err = e.err
}
}()
}
e.MustEncode(v)
return
}
// MustEncode is like Encode, but panics if unable to Encode.
//
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | true |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ugorji/go/codec/goversion_arrayof_lt_go15.go | vendor/github.com/ugorji/go/codec/goversion_arrayof_lt_go15.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
//go:build !go1.5
// +build !go1.5
package codec
import (
"errors"
"reflect"
)
const reflectArrayOfSupported = false
var errNoReflectArrayOf = errors.New("codec: reflect.ArrayOf unsupported by this go version")
func reflectArrayOf(count int, elem reflect.Type) reflect.Type {
panic(errNoReflectArrayOf)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ugorji/go/codec/simple.go | vendor/github.com/ugorji/go/codec/simple.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
package codec
import (
"math"
"reflect"
"time"
)
const (
_ uint8 = iota
simpleVdNil = 1
simpleVdFalse = 2
simpleVdTrue = 3
simpleVdFloat32 = 4
simpleVdFloat64 = 5
// each lasts for 4 (ie n, n+1, n+2, n+3)
simpleVdPosInt = 8
simpleVdNegInt = 12
simpleVdTime = 24
// containers: each lasts for 4 (ie n, n+1, n+2, ... n+7)
simpleVdString = 216
simpleVdByteArray = 224
simpleVdArray = 232
simpleVdMap = 240
simpleVdExt = 248
)
var simpledescNames = map[byte]string{
simpleVdNil: "null",
simpleVdFalse: "false",
simpleVdTrue: "true",
simpleVdFloat32: "float32",
simpleVdFloat64: "float64",
simpleVdPosInt: "+int",
simpleVdNegInt: "-int",
simpleVdTime: "time",
simpleVdString: "string",
simpleVdByteArray: "binary",
simpleVdArray: "array",
simpleVdMap: "map",
simpleVdExt: "ext",
}
func simpledesc(bd byte) (s string) {
s = simpledescNames[bd]
if s == "" {
s = "unknown"
}
return
}
type simpleEncDriver struct {
noBuiltInTypes
encDriverNoopContainerWriter
encDriverNoState
h *SimpleHandle
// b [8]byte
e Encoder
}
func (e *simpleEncDriver) encoder() *Encoder {
return &e.e
}
func (e *simpleEncDriver) EncodeNil() {
e.e.encWr.writen1(simpleVdNil)
}
func (e *simpleEncDriver) EncodeBool(b bool) {
if e.h.EncZeroValuesAsNil && e.e.c != containerMapKey && !b {
e.EncodeNil()
return
}
if b {
e.e.encWr.writen1(simpleVdTrue)
} else {
e.e.encWr.writen1(simpleVdFalse)
}
}
func (e *simpleEncDriver) EncodeFloat32(f float32) {
if e.h.EncZeroValuesAsNil && e.e.c != containerMapKey && f == 0.0 {
e.EncodeNil()
return
}
e.e.encWr.writen1(simpleVdFloat32)
bigen.writeUint32(e.e.w(), math.Float32bits(f))
}
func (e *simpleEncDriver) EncodeFloat64(f float64) {
if e.h.EncZeroValuesAsNil && e.e.c != containerMapKey && f == 0.0 {
e.EncodeNil()
return
}
e.e.encWr.writen1(simpleVdFloat64)
bigen.writeUint64(e.e.w(), math.Float64bits(f))
}
func (e *simpleEncDriver) EncodeInt(v int64) {
if v < 0 {
e.encUint(uint64(-v), simpleVdNegInt)
} else {
e.encUint(uint64(v), simpleVdPosInt)
}
}
func (e *simpleEncDriver) EncodeUint(v uint64) {
e.encUint(v, simpleVdPosInt)
}
func (e *simpleEncDriver) encUint(v uint64, bd uint8) {
if e.h.EncZeroValuesAsNil && e.e.c != containerMapKey && v == 0 {
e.EncodeNil()
return
}
if v <= math.MaxUint8 {
e.e.encWr.writen2(bd, uint8(v))
} else if v <= math.MaxUint16 {
e.e.encWr.writen1(bd + 1)
bigen.writeUint16(e.e.w(), uint16(v))
} else if v <= math.MaxUint32 {
e.e.encWr.writen1(bd + 2)
bigen.writeUint32(e.e.w(), uint32(v))
} else { // if v <= math.MaxUint64 {
e.e.encWr.writen1(bd + 3)
bigen.writeUint64(e.e.w(), v)
}
}
func (e *simpleEncDriver) encLen(bd byte, length int) {
if length == 0 {
e.e.encWr.writen1(bd)
} else if length <= math.MaxUint8 {
e.e.encWr.writen1(bd + 1)
e.e.encWr.writen1(uint8(length))
} else if length <= math.MaxUint16 {
e.e.encWr.writen1(bd + 2)
bigen.writeUint16(e.e.w(), uint16(length))
} else if int64(length) <= math.MaxUint32 {
e.e.encWr.writen1(bd + 3)
bigen.writeUint32(e.e.w(), uint32(length))
} else {
e.e.encWr.writen1(bd + 4)
bigen.writeUint64(e.e.w(), uint64(length))
}
}
func (e *simpleEncDriver) EncodeExt(v interface{}, basetype reflect.Type, xtag uint64, ext Ext) {
var bs0, bs []byte
if ext == SelfExt {
bs0 = e.e.blist.get(1024)
bs = bs0
e.e.sideEncode(v, basetype, &bs)
} else {
bs = ext.WriteExt(v)
}
if bs == nil {
e.EncodeNil()
goto END
}
e.encodeExtPreamble(uint8(xtag), len(bs))
e.e.encWr.writeb(bs)
END:
if ext == SelfExt {
e.e.blist.put(bs)
if !byteSliceSameData(bs0, bs) {
e.e.blist.put(bs0)
}
}
}
func (e *simpleEncDriver) EncodeRawExt(re *RawExt) {
e.encodeExtPreamble(uint8(re.Tag), len(re.Data))
e.e.encWr.writeb(re.Data)
}
func (e *simpleEncDriver) encodeExtPreamble(xtag byte, length int) {
e.encLen(simpleVdExt, length)
e.e.encWr.writen1(xtag)
}
func (e *simpleEncDriver) WriteArrayStart(length int) {
e.encLen(simpleVdArray, length)
}
func (e *simpleEncDriver) WriteMapStart(length int) {
e.encLen(simpleVdMap, length)
}
func (e *simpleEncDriver) EncodeString(v string) {
if e.h.EncZeroValuesAsNil && e.e.c != containerMapKey && v == "" {
e.EncodeNil()
return
}
if e.h.StringToRaw {
e.encLen(simpleVdByteArray, len(v))
} else {
e.encLen(simpleVdString, len(v))
}
e.e.encWr.writestr(v)
}
func (e *simpleEncDriver) EncodeStringBytesRaw(v []byte) {
// if e.h.EncZeroValuesAsNil && e.c != containerMapKey && v == nil {
if v == nil {
e.EncodeNil()
return
}
e.encLen(simpleVdByteArray, len(v))
e.e.encWr.writeb(v)
}
func (e *simpleEncDriver) EncodeTime(t time.Time) {
// if e.h.EncZeroValuesAsNil && e.c != containerMapKey && t.IsZero() {
if t.IsZero() {
e.EncodeNil()
return
}
v, err := t.MarshalBinary()
e.e.onerror(err)
e.e.encWr.writen2(simpleVdTime, uint8(len(v)))
e.e.encWr.writeb(v)
}
//------------------------------------
type simpleDecDriver struct {
h *SimpleHandle
bdAndBdread
_ bool
noBuiltInTypes
decDriverNoopContainerReader
decDriverNoopNumberHelper
d Decoder
}
func (d *simpleDecDriver) decoder() *Decoder {
return &d.d
}
func (d *simpleDecDriver) descBd() string {
return sprintf("%v (%s)", d.bd, simpledesc(d.bd))
}
func (d *simpleDecDriver) readNextBd() {
d.bd = d.d.decRd.readn1()
d.bdRead = true
}
func (d *simpleDecDriver) advanceNil() (null bool) {
if !d.bdRead {
d.readNextBd()
}
if d.bd == simpleVdNil {
d.bdRead = false
return true // null = true
}
return
}
func (d *simpleDecDriver) ContainerType() (vt valueType) {
if !d.bdRead {
d.readNextBd()
}
switch d.bd {
case simpleVdNil:
d.bdRead = false
return valueTypeNil
case simpleVdByteArray, simpleVdByteArray + 1,
simpleVdByteArray + 2, simpleVdByteArray + 3, simpleVdByteArray + 4:
return valueTypeBytes
case simpleVdString, simpleVdString + 1,
simpleVdString + 2, simpleVdString + 3, simpleVdString + 4:
return valueTypeString
case simpleVdArray, simpleVdArray + 1,
simpleVdArray + 2, simpleVdArray + 3, simpleVdArray + 4:
return valueTypeArray
case simpleVdMap, simpleVdMap + 1,
simpleVdMap + 2, simpleVdMap + 3, simpleVdMap + 4:
return valueTypeMap
}
return valueTypeUnset
}
func (d *simpleDecDriver) TryNil() bool {
return d.advanceNil()
}
func (d *simpleDecDriver) decFloat() (f float64, ok bool) {
ok = true
switch d.bd {
case simpleVdFloat32:
f = float64(math.Float32frombits(bigen.Uint32(d.d.decRd.readn4())))
case simpleVdFloat64:
f = math.Float64frombits(bigen.Uint64(d.d.decRd.readn8()))
default:
ok = false
}
return
}
func (d *simpleDecDriver) decInteger() (ui uint64, neg, ok bool) {
ok = true
switch d.bd {
case simpleVdPosInt:
ui = uint64(d.d.decRd.readn1())
case simpleVdPosInt + 1:
ui = uint64(bigen.Uint16(d.d.decRd.readn2()))
case simpleVdPosInt + 2:
ui = uint64(bigen.Uint32(d.d.decRd.readn4()))
case simpleVdPosInt + 3:
ui = uint64(bigen.Uint64(d.d.decRd.readn8()))
case simpleVdNegInt:
ui = uint64(d.d.decRd.readn1())
neg = true
case simpleVdNegInt + 1:
ui = uint64(bigen.Uint16(d.d.decRd.readn2()))
neg = true
case simpleVdNegInt + 2:
ui = uint64(bigen.Uint32(d.d.decRd.readn4()))
neg = true
case simpleVdNegInt + 3:
ui = uint64(bigen.Uint64(d.d.decRd.readn8()))
neg = true
default:
ok = false
// d.d.errorf("integer only valid from pos/neg integer1..8. Invalid descriptor: %v", d.bd)
}
// DO NOT do this check below, because callers may only want the unsigned value:
//
// if ui > math.MaxInt64 {
// d.d.errorf("decIntAny: Integer out of range for signed int64: %v", ui)
// return
// }
return
}
func (d *simpleDecDriver) DecodeInt64() (i int64) {
if d.advanceNil() {
return
}
i = decNegintPosintFloatNumberHelper{&d.d}.int64(d.decInteger())
d.bdRead = false
return
}
func (d *simpleDecDriver) DecodeUint64() (ui uint64) {
if d.advanceNil() {
return
}
ui = decNegintPosintFloatNumberHelper{&d.d}.uint64(d.decInteger())
d.bdRead = false
return
}
func (d *simpleDecDriver) DecodeFloat64() (f float64) {
if d.advanceNil() {
return
}
f = decNegintPosintFloatNumberHelper{&d.d}.float64(d.decFloat())
d.bdRead = false
return
}
// bool can be decoded from bool only (single byte).
func (d *simpleDecDriver) DecodeBool() (b bool) {
if d.advanceNil() {
return
}
if d.bd == simpleVdFalse {
} else if d.bd == simpleVdTrue {
b = true
} else {
d.d.errorf("cannot decode bool - %s: %x", msgBadDesc, d.bd)
}
d.bdRead = false
return
}
func (d *simpleDecDriver) ReadMapStart() (length int) {
if d.advanceNil() {
return containerLenNil
}
d.bdRead = false
return d.decLen()
}
func (d *simpleDecDriver) ReadArrayStart() (length int) {
if d.advanceNil() {
return containerLenNil
}
d.bdRead = false
return d.decLen()
}
func (d *simpleDecDriver) uint2Len(ui uint64) int {
if chkOvf.Uint(ui, intBitsize) {
d.d.errorf("overflow integer: %v", ui)
}
return int(ui)
}
func (d *simpleDecDriver) decLen() int {
switch d.bd & 7 { // d.bd % 8 {
case 0:
return 0
case 1:
return int(d.d.decRd.readn1())
case 2:
return int(bigen.Uint16(d.d.decRd.readn2()))
case 3:
return d.uint2Len(uint64(bigen.Uint32(d.d.decRd.readn4())))
case 4:
return d.uint2Len(bigen.Uint64(d.d.decRd.readn8()))
}
d.d.errorf("cannot read length: bd%%8 must be in range 0..4. Got: %d", d.bd%8)
return -1
}
func (d *simpleDecDriver) DecodeStringAsBytes() (s []byte) {
return d.DecodeBytes(nil)
}
func (d *simpleDecDriver) DecodeBytes(bs []byte) (bsOut []byte) {
d.d.decByteState = decByteStateNone
if d.advanceNil() {
return
}
// check if an "array" of uint8's (see ContainerType for how to infer if an array)
if d.bd >= simpleVdArray && d.bd <= simpleVdMap+4 {
if bs == nil {
d.d.decByteState = decByteStateReuseBuf
bs = d.d.b[:]
}
slen := d.ReadArrayStart()
var changed bool
if bs, changed = usableByteSlice(bs, slen); changed {
d.d.decByteState = decByteStateNone
}
for i := 0; i < len(bs); i++ {
bs[i] = uint8(chkOvf.UintV(d.DecodeUint64(), 8))
}
for i := len(bs); i < slen; i++ {
bs = append(bs, uint8(chkOvf.UintV(d.DecodeUint64(), 8)))
}
return bs
}
clen := d.decLen()
d.bdRead = false
if d.d.zerocopy() {
d.d.decByteState = decByteStateZerocopy
return d.d.decRd.rb.readx(uint(clen))
}
if bs == nil {
d.d.decByteState = decByteStateReuseBuf
bs = d.d.b[:]
}
return decByteSlice(d.d.r(), clen, d.d.h.MaxInitLen, bs)
}
func (d *simpleDecDriver) DecodeTime() (t time.Time) {
if d.advanceNil() {
return
}
if d.bd != simpleVdTime {
d.d.errorf("invalid descriptor for time.Time - expect 0x%x, received 0x%x", simpleVdTime, d.bd)
}
d.bdRead = false
clen := uint(d.d.decRd.readn1())
b := d.d.decRd.readx(clen)
d.d.onerror((&t).UnmarshalBinary(b))
return
}
func (d *simpleDecDriver) DecodeExt(rv interface{}, basetype reflect.Type, xtag uint64, ext Ext) {
if xtag > 0xff {
d.d.errorf("ext: tag must be <= 0xff; got: %v", xtag)
}
if d.advanceNil() {
return
}
xbs, realxtag1, zerocopy := d.decodeExtV(ext != nil, uint8(xtag))
realxtag := uint64(realxtag1)
if ext == nil {
re := rv.(*RawExt)
re.Tag = realxtag
re.setData(xbs, zerocopy)
} else if ext == SelfExt {
d.d.sideDecode(rv, basetype, xbs)
} else {
ext.ReadExt(rv, xbs)
}
}
func (d *simpleDecDriver) decodeExtV(verifyTag bool, tag byte) (xbs []byte, xtag byte, zerocopy bool) {
switch d.bd {
case simpleVdExt, simpleVdExt + 1, simpleVdExt + 2, simpleVdExt + 3, simpleVdExt + 4:
l := d.decLen()
xtag = d.d.decRd.readn1()
if verifyTag && xtag != tag {
d.d.errorf("wrong extension tag. Got %b. Expecting: %v", xtag, tag)
}
if d.d.bytes {
xbs = d.d.decRd.rb.readx(uint(l))
zerocopy = true
} else {
xbs = decByteSlice(d.d.r(), l, d.d.h.MaxInitLen, d.d.b[:])
}
case simpleVdByteArray, simpleVdByteArray + 1,
simpleVdByteArray + 2, simpleVdByteArray + 3, simpleVdByteArray + 4:
xbs = d.DecodeBytes(nil)
default:
d.d.errorf("ext - %s - expecting extensions/bytearray, got: 0x%x", msgBadDesc, d.bd)
}
d.bdRead = false
return
}
func (d *simpleDecDriver) DecodeNaked() {
if !d.bdRead {
d.readNextBd()
}
n := d.d.naked()
var decodeFurther bool
switch d.bd {
case simpleVdNil:
n.v = valueTypeNil
case simpleVdFalse:
n.v = valueTypeBool
n.b = false
case simpleVdTrue:
n.v = valueTypeBool
n.b = true
case simpleVdPosInt, simpleVdPosInt + 1, simpleVdPosInt + 2, simpleVdPosInt + 3:
if d.h.SignedInteger {
n.v = valueTypeInt
n.i = d.DecodeInt64()
} else {
n.v = valueTypeUint
n.u = d.DecodeUint64()
}
case simpleVdNegInt, simpleVdNegInt + 1, simpleVdNegInt + 2, simpleVdNegInt + 3:
n.v = valueTypeInt
n.i = d.DecodeInt64()
case simpleVdFloat32:
n.v = valueTypeFloat
n.f = d.DecodeFloat64()
case simpleVdFloat64:
n.v = valueTypeFloat
n.f = d.DecodeFloat64()
case simpleVdTime:
n.v = valueTypeTime
n.t = d.DecodeTime()
case simpleVdString, simpleVdString + 1,
simpleVdString + 2, simpleVdString + 3, simpleVdString + 4:
n.v = valueTypeString
n.s = d.d.stringZC(d.DecodeStringAsBytes())
case simpleVdByteArray, simpleVdByteArray + 1,
simpleVdByteArray + 2, simpleVdByteArray + 3, simpleVdByteArray + 4:
d.d.fauxUnionReadRawBytes(false)
case simpleVdExt, simpleVdExt + 1, simpleVdExt + 2, simpleVdExt + 3, simpleVdExt + 4:
n.v = valueTypeExt
l := d.decLen()
n.u = uint64(d.d.decRd.readn1())
if d.d.bytes {
n.l = d.d.decRd.rb.readx(uint(l))
} else {
n.l = decByteSlice(d.d.r(), l, d.d.h.MaxInitLen, d.d.b[:])
}
case simpleVdArray, simpleVdArray + 1, simpleVdArray + 2,
simpleVdArray + 3, simpleVdArray + 4:
n.v = valueTypeArray
decodeFurther = true
case simpleVdMap, simpleVdMap + 1, simpleVdMap + 2, simpleVdMap + 3, simpleVdMap + 4:
n.v = valueTypeMap
decodeFurther = true
default:
d.d.errorf("cannot infer value - %s 0x%x", msgBadDesc, d.bd)
}
if !decodeFurther {
d.bdRead = false
}
}
func (d *simpleDecDriver) nextValueBytes(v0 []byte) (v []byte) {
if !d.bdRead {
d.readNextBd()
}
v = v0
var h = decNextValueBytesHelper{d: &d.d}
var cursor = d.d.rb.c - 1
h.append1(&v, d.bd)
v = d.nextValueBytesBdReadR(v)
d.bdRead = false
h.bytesRdV(&v, cursor)
return
}
func (d *simpleDecDriver) nextValueBytesR(v0 []byte) (v []byte) {
d.readNextBd()
v = v0
var h = decNextValueBytesHelper{d: &d.d}
h.append1(&v, d.bd)
return d.nextValueBytesBdReadR(v)
}
func (d *simpleDecDriver) nextValueBytesBdReadR(v0 []byte) (v []byte) {
v = v0
var h = decNextValueBytesHelper{d: &d.d}
c := d.bd
var length uint
switch c {
case simpleVdNil, simpleVdFalse, simpleVdTrue, simpleVdString, simpleVdByteArray:
// pass
case simpleVdPosInt, simpleVdNegInt:
h.append1(&v, d.d.decRd.readn1())
case simpleVdPosInt + 1, simpleVdNegInt + 1:
h.appendN(&v, d.d.decRd.readx(2)...)
case simpleVdPosInt + 2, simpleVdNegInt + 2, simpleVdFloat32:
h.appendN(&v, d.d.decRd.readx(4)...)
case simpleVdPosInt + 3, simpleVdNegInt + 3, simpleVdFloat64:
h.appendN(&v, d.d.decRd.readx(8)...)
case simpleVdTime:
c = d.d.decRd.readn1()
h.append1(&v, c)
h.appendN(&v, d.d.decRd.readx(uint(c))...)
default:
switch c & 7 { // c % 8 {
case 0:
length = 0
case 1:
b := d.d.decRd.readn1()
length = uint(b)
h.append1(&v, b)
case 2:
x := d.d.decRd.readn2()
length = uint(bigen.Uint16(x))
h.appendN(&v, x[:]...)
case 3:
x := d.d.decRd.readn4()
length = uint(bigen.Uint32(x))
h.appendN(&v, x[:]...)
case 4:
x := d.d.decRd.readn8()
length = uint(bigen.Uint64(x))
h.appendN(&v, x[:]...)
}
bExt := c >= simpleVdExt && c <= simpleVdExt+7
bStr := c >= simpleVdString && c <= simpleVdString+7
bByteArray := c >= simpleVdByteArray && c <= simpleVdByteArray+7
bArray := c >= simpleVdArray && c <= simpleVdArray+7
bMap := c >= simpleVdMap && c <= simpleVdMap+7
if !(bExt || bStr || bByteArray || bArray || bMap) {
d.d.errorf("cannot infer value - %s 0x%x", msgBadDesc, c)
}
if bExt {
h.append1(&v, d.d.decRd.readn1()) // tag
}
if length == 0 {
break
}
if bArray {
for i := uint(0); i < length; i++ {
v = d.nextValueBytesR(v)
}
} else if bMap {
for i := uint(0); i < length; i++ {
v = d.nextValueBytesR(v)
v = d.nextValueBytesR(v)
}
} else {
h.appendN(&v, d.d.decRd.readx(length)...)
}
}
return
}
//------------------------------------
// SimpleHandle is a Handle for a very simple encoding format.
//
// simple is a simplistic codec similar to binc, but not as compact.
// - Encoding of a value is always preceded by the descriptor byte (bd)
// - True, false, nil are encoded fully in 1 byte (the descriptor)
// - Integers (intXXX, uintXXX) are encoded in 1, 2, 4 or 8 bytes (plus a descriptor byte).
// There are positive (uintXXX and intXXX >= 0) and negative (intXXX < 0) integers.
// - Floats are encoded in 4 or 8 bytes (plus a descriptor byte)
// - Length of containers (strings, bytes, array, map, extensions)
// are encoded in 0, 1, 2, 4 or 8 bytes.
// Zero-length containers have no length encoded.
// For others, the number of bytes is given by pow(2, bd%3)
// - maps are encoded as [bd] [length] [[key][value]]...
// - arrays are encoded as [bd] [length] [value]...
// - extensions are encoded as [bd] [length] [tag] [byte]...
// - strings/bytearrays are encoded as [bd] [length] [byte]...
// - time.Time are encoded as [bd] [length] [byte]...
//
// The full spec will be published soon.
type SimpleHandle struct {
binaryEncodingType
BasicHandle
// EncZeroValuesAsNil says to encode zero values for numbers, bool, string, etc as nil
EncZeroValuesAsNil bool
}
// Name returns the name of the handle: simple
func (h *SimpleHandle) Name() string { return "simple" }
func (h *SimpleHandle) desc(bd byte) string { return simpledesc(bd) }
func (h *SimpleHandle) newEncDriver() encDriver {
var e = &simpleEncDriver{h: h}
e.e.e = e
e.e.init(h)
e.reset()
return e
}
func (h *SimpleHandle) newDecDriver() decDriver {
d := &simpleDecDriver{h: h}
d.d.d = d
d.d.init(h)
d.reset()
return d
}
var _ decDriver = (*simpleDecDriver)(nil)
var _ encDriver = (*simpleEncDriver)(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/ugorji/go/codec/goversion_fmt_time_gte_go15.go | vendor/github.com/ugorji/go/codec/goversion_fmt_time_gte_go15.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
//go:build go1.5
// +build go1.5
package codec
import "time"
func fmtTime(t time.Time, fmt string, b []byte) []byte {
return t.AppendFormat(b, fmt)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ugorji/go/codec/goversion_unexportedembeddedptr_lt_go110.go | vendor/github.com/ugorji/go/codec/goversion_unexportedembeddedptr_lt_go110.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
//go:build !go1.10
// +build !go1.10
package codec
const allowSetUnexportedEmbeddedPtr = 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/ugorji/go/codec/goversion_growslice_unsafe_gte_go120.go | vendor/github.com/ugorji/go/codec/goversion_growslice_unsafe_gte_go120.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
//go:build go1.20 && !safe && !codec.safe && !appengine
// +build go1.20,!safe,!codec.safe,!appengine
package codec
import (
_ "reflect" // needed for go linkname(s)
"unsafe"
)
func growslice(typ unsafe.Pointer, old unsafeSlice, num int) (s unsafeSlice) {
// culled from GOROOT/runtime/slice.go
num -= old.Cap - old.Len
s = rtgrowslice(old.Data, old.Cap+num, old.Cap, num, typ)
s.Len = old.Len
return
}
//go:linkname rtgrowslice runtime.growslice
//go:noescape
func rtgrowslice(oldPtr unsafe.Pointer, newLen, oldCap, num int, typ unsafe.Pointer) unsafeSlice
// //go:linkname growslice reflect.growslice
// //go:noescape
// func growslice(typ unsafe.Pointer, old unsafeSlice, cap int) unsafeSlice
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ugorji/go/codec/gen.generated.go | vendor/github.com/ugorji/go/codec/gen.generated.go | // +build codecgen.exec
// Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
package codec
// DO NOT EDIT. THIS FILE IS AUTO-GENERATED FROM gen-dec-(map|array).go.tmpl
const genDecMapTmpl = `
{{var "v"}} := *{{ .Varname }}
{{var "l"}} := z.DecReadMapStart()
if {{var "l"}} == codecSelferDecContainerLenNil{{xs}} {
*{{ .Varname }} = nil
} else {
if {{var "v"}} == nil {
{{var "rl"}} := z.DecInferLen({{var "l"}}, z.DecBasicHandle().MaxInitLen, {{ .Size }})
{{var "v"}} = make(map[{{ .KTyp }}]{{ .Typ }}, {{var "rl"}})
*{{ .Varname }} = {{var "v"}}
}
{{ $mk := var "mk" -}}
var {{ $mk }} {{ .KTyp }}
var {{var "mv"}} {{ .Typ }}
var {{var "mg"}}, {{var "mdn"}} {{if decElemKindPtr}}, {{var "ms"}}, {{var "mok"}}{{end}} bool
if z.DecBasicHandle().MapValueReset {
{{if decElemKindPtr}}{{var "mg"}} = true
{{else if decElemKindIntf}}if !z.DecBasicHandle().InterfaceReset { {{var "mg"}} = true }
{{else if not decElemKindImmutable}}{{var "mg"}} = true
{{end}} }
if {{var "l"}} != 0 {
{{var "hl"}} := {{var "l"}} > 0
for {{var "j"}} := 0; z.DecContainerNext({{var "j"}}, {{var "l"}}, {{var "hl"}}); {{var "j"}}++ {
z.DecReadMapElemKey()
{{ if eq .KTyp "string" -}}
{{ decLineVarK $mk -}}{{- /* decLineVarKStrZC $mk */ -}}
{{ else -}}
{{ decLineVarK $mk -}}
{{ end -}}
{{ if eq .KTyp "interface{}" }}{{/* // special case if a byte array. */ -}}
if {{var "bv"}}, {{var "bok"}} := {{var "mk"}}.([]byte); {{var "bok"}} {
{{var "mk"}} = z.DecStringZC({{var "bv"}})
}
{{ end -}}
{{if decElemKindPtr -}}
{{var "ms"}} = true
{{end -}}
if {{var "mg"}} {
{{if decElemKindPtr -}}
{{var "mv"}}, {{var "mok"}} = {{var "v"}}[{{ $mk }}]
if {{var "mok"}} {
{{var "ms"}} = false
}
{{else -}}
{{var "mv"}} = {{var "v"}}[{{ $mk }}]
{{end -}}
} {{if not decElemKindImmutable}}else { {{var "mv"}} = {{decElemZero}} }{{end}}
z.DecReadMapElemValue()
{{var "mdn"}} = false
{{ $x := printf "%vmv%v" .TempVar .Rand }}{{ $y := printf "%vmdn%v" .TempVar .Rand }}{{ decLineVar $x $y -}}
if {{var "mdn"}} {
{{var "v"}}[{{ $mk }}] = {{decElemZero}}
} else {{if decElemKindPtr}} if {{var "ms"}} {{end}} {
{{var "v"}}[{{ $mk }}] = {{var "mv"}}
}
}
} // else len==0: leave as-is (do not clear map entries)
z.DecReadMapEnd()
}
`
const genDecListTmpl = `
{{var "v"}} := {{if not isArray}}*{{end}}{{ .Varname }}
{{var "h"}}, {{var "l"}} := z.DecSliceHelperStart() {{/* // helper, containerLenS */}}
{{if not isArray -}}
var {{var "c"}} bool {{/* // changed */}}
_ = {{var "c"}}
if {{var "h"}}.IsNil {
if {{var "v"}} != nil {
{{var "v"}} = nil
{{var "c"}} = true
}
} else {{end -}}
if {{var "l"}} == 0 {
{{if isSlice -}}
if {{var "v"}} == nil {
{{var "v"}} = []{{ .Typ }}{}
{{var "c"}} = true
} else if len({{var "v"}}) != 0 {
{{var "v"}} = {{var "v"}}[:0]
{{var "c"}} = true
} {{else if isChan }}if {{var "v"}} == nil {
{{var "v"}} = make({{ .CTyp }}, 0)
{{var "c"}} = true
}
{{end -}}
} else {
{{var "hl"}} := {{var "l"}} > 0
var {{var "rl"}} int
_ = {{var "rl"}}
{{if isSlice }} if {{var "hl"}} {
if {{var "l"}} > cap({{var "v"}}) {
{{var "rl"}} = z.DecInferLen({{var "l"}}, z.DecBasicHandle().MaxInitLen, {{ .Size }})
if {{var "rl"}} <= cap({{var "v"}}) {
{{var "v"}} = {{var "v"}}[:{{var "rl"}}]
} else {
{{var "v"}} = make([]{{ .Typ }}, {{var "rl"}})
}
{{var "c"}} = true
} else if {{var "l"}} != len({{var "v"}}) {
{{var "v"}} = {{var "v"}}[:{{var "l"}}]
{{var "c"}} = true
}
}
{{end -}}
var {{var "j"}} int
{{/* // var {{var "dn"}} bool */ -}}
for {{var "j"}} = 0; z.DecContainerNext({{var "j"}}, {{var "l"}}, {{var "hl"}}); {{var "j"}}++ {
{{if not isArray}} if {{var "j"}} == 0 && {{var "v"}} == nil {
if {{var "hl"}} {
{{var "rl"}} = z.DecInferLen({{var "l"}}, z.DecBasicHandle().MaxInitLen, {{ .Size }})
} else {
{{var "rl"}} = {{if isSlice}}8{{else if isChan}}64{{end}}
}
{{var "v"}} = make({{if isSlice}}[]{{ .Typ }}{{else if isChan}}{{.CTyp}}{{end}}, {{var "rl"}})
{{var "c"}} = true
}
{{end -}}
{{var "h"}}.ElemContainerState({{var "j"}})
{{/* {{var "dn"}} = r.TryDecodeAsNil() */}}{{/* commented out, as decLineVar handles this already each time */ -}}
{{if isChan}}{{ $x := printf "%[1]vvcx%[2]v" .TempVar .Rand }}var {{$x}} {{ .Typ }}
{{ decLineVar $x -}}
{{var "v"}} <- {{ $x }}
{{else}}{{/* // if indefinite, etc, then expand the slice if necessary */ -}}
var {{var "db"}} bool
if {{var "j"}} >= len({{var "v"}}) {
{{if isSlice }} {{var "v"}} = append({{var "v"}}, {{ zero }})
{{var "c"}} = true
{{else}} z.DecArrayCannotExpand(len(v), {{var "j"}}+1); {{var "db"}} = true
{{end -}}
}
if {{var "db"}} {
z.DecSwallow()
} else {
{{ $x := printf "%[1]vv%[2]v[%[1]vj%[2]v]" .TempVar .Rand }}{{ decLineVar $x -}}
}
{{end -}}
}
{{if isSlice}} if {{var "j"}} < len({{var "v"}}) {
{{var "v"}} = {{var "v"}}[:{{var "j"}}]
{{var "c"}} = true
} else if {{var "j"}} == 0 && {{var "v"}} == nil {
{{var "v"}} = []{{ .Typ }}{}
{{var "c"}} = true
}
{{end -}}
}
{{var "h"}}.End()
{{if not isArray }}if {{var "c"}} {
*{{ .Varname }} = {{var "v"}}
}
{{end -}}
`
const genEncChanTmpl = `
{{.Label}}:
switch timeout{{.Sfx}} := z.EncBasicHandle().ChanRecvTimeout; {
case timeout{{.Sfx}} == 0: // only consume available
for {
select {
case b{{.Sfx}} := <-{{.Chan}}:
{{ .Slice }} = append({{.Slice}}, b{{.Sfx}})
default:
break {{.Label}}
}
}
case timeout{{.Sfx}} > 0: // consume until timeout
tt{{.Sfx}} := time.NewTimer(timeout{{.Sfx}})
for {
select {
case b{{.Sfx}} := <-{{.Chan}}:
{{.Slice}} = append({{.Slice}}, b{{.Sfx}})
case <-tt{{.Sfx}}.C:
// close(tt.C)
break {{.Label}}
}
}
default: // consume until close
for b{{.Sfx}} := range {{.Chan}} {
{{.Slice}} = append({{.Slice}}, b{{.Sfx}})
}
}
`
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ugorji/go/codec/helper_unsafe_compiler_gc.go | vendor/github.com/ugorji/go/codec/helper_unsafe_compiler_gc.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
//go:build !safe && !codec.safe && !appengine && go1.9 && gc
// +build !safe,!codec.safe,!appengine,go1.9,gc
package codec
import (
"reflect"
_ "runtime" // needed for go linkname(s)
"unsafe"
)
// keep in sync with
//
// $GOROOT/src/cmd/compile/internal/gc/reflect.go: MAXKEYSIZE, MAXELEMSIZE
// $GOROOT/src/runtime/map.go: maxKeySize, maxElemSize
// $GOROOT/src/reflect/type.go: maxKeySize, maxElemSize
//
// We use these to determine whether the type is stored indirectly in the map or not.
const (
// mapMaxKeySize = 128
mapMaxElemSize = 128
)
func unsafeGrowslice(typ unsafe.Pointer, old unsafeSlice, cap, incr int) (v unsafeSlice) {
return growslice(typ, old, cap+incr)
}
// func rvType(rv reflect.Value) reflect.Type {
// return rvPtrToType(((*unsafeReflectValue)(unsafe.Pointer(&rv))).typ)
// // return rv.Type()
// }
// mapStoresElemIndirect tells if the element type is stored indirectly in the map.
//
// This is used to determine valIsIndirect which is passed into mapSet/mapGet calls.
//
// If valIsIndirect doesn't matter, then just return false and ignore the value
// passed in mapGet/mapSet calls
func mapStoresElemIndirect(elemsize uintptr) bool {
return elemsize > mapMaxElemSize
}
func mapSet(m, k, v reflect.Value, keyFastKind mapKeyFastKind, valIsIndirect, valIsRef bool) {
var urv = (*unsafeReflectValue)(unsafe.Pointer(&k))
var kptr = unsafeMapKVPtr(urv)
urv = (*unsafeReflectValue)(unsafe.Pointer(&v))
var vtyp = urv.typ
var vptr = unsafeMapKVPtr(urv)
urv = (*unsafeReflectValue)(unsafe.Pointer(&m))
mptr := rvRefPtr(urv)
var vvptr unsafe.Pointer
// mapassign_fastXXX don't take indirect into account.
// It was hard to infer what makes it work all the time.
// Sometimes, we got vvptr == nil when we dereferenced vvptr (if valIsIndirect).
// Consequently, only use fastXXX functions if !valIsIndirect
if valIsIndirect {
vvptr = mapassign(urv.typ, mptr, kptr)
typedmemmove(vtyp, vvptr, vptr)
// reflect_mapassign(urv.typ, mptr, kptr, vptr)
return
}
switch keyFastKind {
case mapKeyFastKind32:
vvptr = mapassign_fast32(urv.typ, mptr, *(*uint32)(kptr))
case mapKeyFastKind32ptr:
vvptr = mapassign_fast32ptr(urv.typ, mptr, *(*unsafe.Pointer)(kptr))
case mapKeyFastKind64:
vvptr = mapassign_fast64(urv.typ, mptr, *(*uint64)(kptr))
case mapKeyFastKind64ptr:
vvptr = mapassign_fast64ptr(urv.typ, mptr, *(*unsafe.Pointer)(kptr))
case mapKeyFastKindStr:
vvptr = mapassign_faststr(urv.typ, mptr, *(*string)(kptr))
default:
vvptr = mapassign(urv.typ, mptr, kptr)
}
// if keyFastKind != 0 && valIsIndirect {
// vvptr = *(*unsafe.Pointer)(vvptr)
// }
typedmemmove(vtyp, vvptr, vptr)
}
func mapGet(m, k, v reflect.Value, keyFastKind mapKeyFastKind, valIsIndirect, valIsRef bool) (_ reflect.Value) {
var urv = (*unsafeReflectValue)(unsafe.Pointer(&k))
var kptr = unsafeMapKVPtr(urv)
urv = (*unsafeReflectValue)(unsafe.Pointer(&m))
mptr := rvRefPtr(urv)
var vvptr unsafe.Pointer
var ok bool
// Note that mapaccess2_fastXXX functions do not check if the value needs to be copied.
// if they do, we should dereference the pointer and return that
switch keyFastKind {
case mapKeyFastKind32, mapKeyFastKind32ptr:
vvptr, ok = mapaccess2_fast32(urv.typ, mptr, *(*uint32)(kptr))
case mapKeyFastKind64, mapKeyFastKind64ptr:
vvptr, ok = mapaccess2_fast64(urv.typ, mptr, *(*uint64)(kptr))
case mapKeyFastKindStr:
vvptr, ok = mapaccess2_faststr(urv.typ, mptr, *(*string)(kptr))
default:
vvptr, ok = mapaccess2(urv.typ, mptr, kptr)
}
if !ok {
return
}
urv = (*unsafeReflectValue)(unsafe.Pointer(&v))
if keyFastKind != 0 && valIsIndirect {
urv.ptr = *(*unsafe.Pointer)(vvptr)
} else if helperUnsafeDirectAssignMapEntry || valIsRef {
urv.ptr = vvptr
} else {
typedmemmove(urv.typ, urv.ptr, vvptr)
}
return v
}
//go:linkname unsafeZeroArr runtime.zeroVal
var unsafeZeroArr [1024]byte
// //go:linkname rvPtrToType reflect.toType
// //go:noescape
// func rvPtrToType(typ unsafe.Pointer) reflect.Type
//go:linkname mapassign_fast32 runtime.mapassign_fast32
//go:noescape
func mapassign_fast32(typ unsafe.Pointer, m unsafe.Pointer, key uint32) unsafe.Pointer
//go:linkname mapassign_fast32ptr runtime.mapassign_fast32ptr
//go:noescape
func mapassign_fast32ptr(typ unsafe.Pointer, m unsafe.Pointer, key unsafe.Pointer) unsafe.Pointer
//go:linkname mapassign_fast64 runtime.mapassign_fast64
//go:noescape
func mapassign_fast64(typ unsafe.Pointer, m unsafe.Pointer, key uint64) unsafe.Pointer
//go:linkname mapassign_fast64ptr runtime.mapassign_fast64ptr
//go:noescape
func mapassign_fast64ptr(typ unsafe.Pointer, m unsafe.Pointer, key unsafe.Pointer) unsafe.Pointer
//go:linkname mapassign_faststr runtime.mapassign_faststr
//go:noescape
func mapassign_faststr(typ unsafe.Pointer, m unsafe.Pointer, s string) unsafe.Pointer
//go:linkname mapaccess2_fast32 runtime.mapaccess2_fast32
//go:noescape
func mapaccess2_fast32(typ unsafe.Pointer, m unsafe.Pointer, key uint32) (val unsafe.Pointer, ok bool)
//go:linkname mapaccess2_fast64 runtime.mapaccess2_fast64
//go:noescape
func mapaccess2_fast64(typ unsafe.Pointer, m unsafe.Pointer, key uint64) (val unsafe.Pointer, ok bool)
//go:linkname mapaccess2_faststr runtime.mapaccess2_faststr
//go:noescape
func mapaccess2_faststr(typ unsafe.Pointer, m unsafe.Pointer, key string) (val unsafe.Pointer, ok 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/ugorji/go/codec/goversion_vendor_lt_go15.go | vendor/github.com/ugorji/go/codec/goversion_vendor_lt_go15.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
//go:build !go1.5
// +build !go1.5
package codec
var genCheckVendor = 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/ugorji/go/codec/goversion_arrayof_gte_go15.go | vendor/github.com/ugorji/go/codec/goversion_arrayof_gte_go15.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
//go:build go1.5
// +build go1.5
package codec
import "reflect"
const reflectArrayOfSupported = true
func reflectArrayOf(count int, elem reflect.Type) reflect.Type {
return reflect.ArrayOf(count, 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/ugorji/go/codec/goversion_makemap_not_unsafe_gte_go110.go | vendor/github.com/ugorji/go/codec/goversion_makemap_not_unsafe_gte_go110.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
//go:build go1.10 && (safe || codec.safe || appengine)
// +build go1.10
// +build safe codec.safe appengine
package codec
import "reflect"
func makeMapReflect(t reflect.Type, size int) reflect.Value {
return reflect.MakeMapWithSize(t, size)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ugorji/go/codec/goversion_unsupported_lt_go14.go | vendor/github.com/ugorji/go/codec/goversion_unsupported_lt_go14.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
//go:build !go1.4
// +build !go1.4
package codec
import "errors"
// This codec package will only work for go1.4 and above.
// This is for the following reasons:
// - go 1.4 was released in 2014
// - go runtime is written fully in go
// - interface only holds pointers
// - reflect.Value is stabilized as 3 words
var errCodecSupportedOnlyFromGo14 = errors.New("codec: go 1.3 and below are not supported")
func init() {
panic(errCodecSupportedOnlyFromGo14)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ugorji/go/codec/goversion_maprange_gte_go112.go | vendor/github.com/ugorji/go/codec/goversion_maprange_gte_go112.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
//go:build go1.12 && (safe || codec.safe || appengine)
// +build go1.12
// +build safe codec.safe appengine
package codec
import "reflect"
type mapIter struct {
t *reflect.MapIter
m reflect.Value
values bool
}
func (t *mapIter) Next() (r bool) {
return t.t.Next()
}
func (t *mapIter) Key() reflect.Value {
return t.t.Key()
}
func (t *mapIter) Value() (r reflect.Value) {
if t.values {
return t.t.Value()
}
return
}
func (t *mapIter) Done() {}
func mapRange(t *mapIter, m, k, v reflect.Value, values bool) {
*t = mapIter{
m: m,
t: m.MapRange(),
values: values,
}
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ugorji/go/codec/gen-helper.generated.go | vendor/github.com/ugorji/go/codec/gen-helper.generated.go | // comment this out // + build ignore
// Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
// Code generated from gen-helper.go.tmpl - DO NOT EDIT.
package codec
import (
"encoding"
"reflect"
)
// GenVersion is the current version of codecgen.
const GenVersion = 28
// This file is used to generate helper code for codecgen.
// The values here i.e. genHelper(En|De)coder are not to be used directly by
// library users. They WILL change continuously and without notice.
// GenHelperEncoder is exported so that it can be used externally by codecgen.
//
// Library users: DO NOT USE IT DIRECTLY or INDIRECTLY. IT WILL CHANGE CONTINOUSLY WITHOUT NOTICE.
func GenHelper() (g genHelper) { return }
type genHelper struct{}
func (genHelper) Encoder(e *Encoder) (ge genHelperEncoder, ee genHelperEncDriver) {
ge = genHelperEncoder{e: e}
ee = genHelperEncDriver{encDriver: e.e}
return
}
func (genHelper) Decoder(d *Decoder) (gd genHelperDecoder, dd genHelperDecDriver) {
gd = genHelperDecoder{d: d}
dd = genHelperDecDriver{decDriver: d.d}
return
}
type genHelperEncDriver struct {
encDriver
}
type genHelperDecDriver struct {
decDriver
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
type genHelperEncoder struct {
M mustHdl
F fastpathT
e *Encoder
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
type genHelperDecoder struct {
C checkOverflow
F fastpathT
d *Decoder
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncBasicHandle() *BasicHandle {
return f.e.h
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncWr() *encWr {
return f.e.w()
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncBinary() bool {
return f.e.be // f.e.hh.isBinaryEncoding()
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) IsJSONHandle() bool {
return f.e.js
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncFallback(iv interface{}) {
// f.e.encodeI(iv, false, false)
f.e.encodeValue(reflect.ValueOf(iv), nil)
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncTextMarshal(iv encoding.TextMarshaler) {
bs, fnerr := iv.MarshalText()
f.e.marshalUtf8(bs, fnerr)
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncJSONMarshal(iv jsonMarshaler) {
bs, fnerr := iv.MarshalJSON()
f.e.marshalAsis(bs, fnerr)
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncBinaryMarshal(iv encoding.BinaryMarshaler) {
bs, fnerr := iv.MarshalBinary()
f.e.marshalRaw(bs, fnerr)
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncRaw(iv Raw) { f.e.rawBytes(iv) }
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) Extension(v interface{}) (xfn *extTypeTagFn) {
return f.e.h.getExtForI(v)
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncExtension(v interface{}, xfFn *extTypeTagFn) {
f.e.e.EncodeExt(v, xfFn.rt, xfFn.tag, xfFn.ext)
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncWriteMapStart(length int) { f.e.mapStart(length) }
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncWriteMapEnd() { f.e.mapEnd() }
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncWriteArrayStart(length int) { f.e.arrayStart(length) }
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncWriteArrayEnd() { f.e.arrayEnd() }
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncWriteArrayElem() { f.e.arrayElem() }
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncWriteMapElemKey() { f.e.mapElemKey() }
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncWriteMapElemValue() { f.e.mapElemValue() }
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncEncodeComplex64(v complex64) { f.e.encodeComplex64(v) }
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncEncodeComplex128(v complex128) { f.e.encodeComplex128(v) }
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncEncode(v interface{}) { f.e.encode(v) }
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncFnGivenAddr(v interface{}) *codecFn {
return f.e.h.fn(reflect.TypeOf(v).Elem())
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncEncodeNumBoolStrKindGivenAddr(v interface{}, encFn *codecFn) {
f.e.encodeValueNonNil(reflect.ValueOf(v).Elem(), encFn)
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncEncodeMapNonNil(v interface{}) {
if skipFastpathTypeSwitchInDirectCall || !fastpathEncodeTypeSwitch(v, f.e) {
f.e.encodeValueNonNil(reflect.ValueOf(v), nil)
}
}
// ---------------- DECODER FOLLOWS -----------------
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecBasicHandle() *BasicHandle {
return f.d.h
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecBinary() bool {
return f.d.be // f.d.hh.isBinaryEncoding()
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecSwallow() { f.d.swallow() }
// // FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
// func (f genHelperDecoder) DecScratchBuffer() []byte {
// return f.d.b[:]
// }
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecScratchArrayBuffer() *[decScratchByteArrayLen]byte {
return &f.d.b
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecFallback(iv interface{}, chkPtr bool) {
rv := reflect.ValueOf(iv)
if chkPtr {
if x, _ := isDecodeable(rv); !x {
f.d.haltAsNotDecodeable(rv)
}
}
f.d.decodeValue(rv, nil)
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecSliceHelperStart() (decSliceHelper, int) {
return f.d.decSliceHelperStart()
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecStructFieldNotFound(index int, name string) {
f.d.structFieldNotFound(index, name)
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecArrayCannotExpand(sliceLen, streamLen int) {
f.d.arrayCannotExpand(sliceLen, streamLen)
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecTextUnmarshal(tm encoding.TextUnmarshaler) {
halt.onerror(tm.UnmarshalText(f.d.d.DecodeStringAsBytes()))
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecJSONUnmarshal(tm jsonUnmarshaler) {
f.d.jsonUnmarshalV(tm)
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecBinaryUnmarshal(bm encoding.BinaryUnmarshaler) {
halt.onerror(bm.UnmarshalBinary(f.d.d.DecodeBytes(nil)))
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecRaw() []byte { return f.d.rawBytes() }
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) IsJSONHandle() bool {
return f.d.js
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) Extension(v interface{}) (xfn *extTypeTagFn) {
return f.d.h.getExtForI(v)
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecExtension(v interface{}, xfFn *extTypeTagFn) {
f.d.d.DecodeExt(v, xfFn.rt, xfFn.tag, xfFn.ext)
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecInferLen(clen, maxlen, unit int) (rvlen int) {
return decInferLen(clen, maxlen, unit)
}
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecReadMapStart() int { return f.d.mapStart(f.d.d.ReadMapStart()) }
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecReadMapEnd() { f.d.mapEnd() }
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecReadArrayStart() int { return f.d.arrayStart(f.d.d.ReadArrayStart()) }
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecReadArrayEnd() { f.d.arrayEnd() }
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecReadArrayElem() { f.d.arrayElem() }
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecReadMapElemKey() { f.d.mapElemKey() }
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecReadMapElemValue() { f.d.mapElemValue() }
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecDecodeFloat32() float32 { return f.d.decodeFloat32() }
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecStringZC(v []byte) string { return f.d.stringZC(v) }
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecodeBytesInto(v []byte) []byte { return f.d.decodeBytesInto(v) }
// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecContainerNext(j, containerLen int, hasLen bool) bool {
// return f.d.containerNext(j, containerLen, hasLen)
// rewriting so it can be inlined
if hasLen {
return j < containerLen
}
return !f.d.checkBreak()
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ugorji/go/codec/goversion_makemap_unsafe_gte_go110.go | vendor/github.com/ugorji/go/codec/goversion_makemap_unsafe_gte_go110.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
//go:build go1.10 && !safe && !codec.safe && !appengine
// +build go1.10,!safe,!codec.safe,!appengine
package codec
import (
"reflect"
"unsafe"
)
func makeMapReflect(typ reflect.Type, size int) (rv reflect.Value) {
t := (*unsafeIntf)(unsafe.Pointer(&typ)).ptr
urv := (*unsafeReflectValue)(unsafe.Pointer(&rv))
urv.typ = t
urv.flag = uintptr(reflect.Map)
urv.ptr = makemap(t, size, nil)
return
}
//go:linkname makemap runtime.makemap
//go:noescape
func makemap(typ unsafe.Pointer, size int, h unsafe.Pointer) unsafe.Pointer
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ugorji/go/codec/goversion_maprange_lt_go112.go | vendor/github.com/ugorji/go/codec/goversion_maprange_lt_go112.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
//go:build go1.7 && !go1.12 && (safe || codec.safe || appengine)
// +build go1.7
// +build !go1.12
// +build safe codec.safe appengine
package codec
import "reflect"
type mapIter struct {
m reflect.Value
keys []reflect.Value
j int
values bool
}
func (t *mapIter) Next() (r bool) {
t.j++
return t.j < len(t.keys)
}
func (t *mapIter) Key() reflect.Value {
return t.keys[t.j]
}
func (t *mapIter) Value() (r reflect.Value) {
if t.values {
return t.m.MapIndex(t.keys[t.j])
}
return
}
func (t *mapIter) Done() {}
func mapRange(t *mapIter, m, k, v reflect.Value, values bool) {
*t = mapIter{
m: m,
keys: m.MapKeys(),
values: values,
j: -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/ugorji/go/codec/doc.go | vendor/github.com/ugorji/go/codec/doc.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
/*
Package codec provides a
High Performance, Feature-Rich Idiomatic Go 1.4+ codec/encoding library
for binc, msgpack, cbor, json.
Supported Serialization formats are:
- msgpack: https://github.com/msgpack/msgpack
- binc: http://github.com/ugorji/binc
- cbor: http://cbor.io http://tools.ietf.org/html/rfc7049
- json: http://json.org http://tools.ietf.org/html/rfc7159
- simple:
This package will carefully use 'package unsafe' for performance reasons in specific places.
You can build without unsafe use by passing the safe or appengine tag
i.e. 'go install -tags=codec.safe ...'.
This library works with both the standard `gc` and the `gccgo` compilers.
For detailed usage information, read the primer at http://ugorji.net/blog/go-codec-primer .
The idiomatic Go support is as seen in other encoding packages in
the standard library (ie json, xml, gob, etc).
Rich Feature Set includes:
- Simple but extremely powerful and feature-rich API
- Support for go 1.4 and above, while selectively using newer APIs for later releases
- Excellent code coverage ( > 90% )
- Very High Performance.
Our extensive benchmarks show us outperforming Gob, Json, Bson, etc by 2-4X.
- Careful selected use of 'unsafe' for targeted performance gains.
- 100% safe mode supported, where 'unsafe' is not used at all.
- Lock-free (sans mutex) concurrency for scaling to 100's of cores
- In-place updates during decode, with option to zero value in maps and slices prior to decode
- Coerce types where appropriate
e.g. decode an int in the stream into a float, decode numbers from formatted strings, etc
- Corner Cases:
Overflows, nil maps/slices, nil values in streams are handled correctly
- Standard field renaming via tags
- Support for omitting empty fields during an encoding
- Encoding from any value and decoding into pointer to any value
(struct, slice, map, primitives, pointers, interface{}, etc)
- Extensions to support efficient encoding/decoding of any named types
- Support encoding.(Binary|Text)(M|Unm)arshaler interfaces
- Support using existence of `IsZero() bool` to determine if a value is a zero value.
Analogous to time.Time.IsZero() bool.
- Decoding without a schema (into a interface{}).
Includes Options to configure what specific map or slice type to use
when decoding an encoded list or map into a nil interface{}
- Mapping a non-interface type to an interface, so we can decode appropriately
into any interface type with a correctly configured non-interface value.
- Encode a struct as an array, and decode struct from an array in the data stream
- Option to encode struct keys as numbers (instead of strings)
(to support structured streams with fields encoded as numeric codes)
- Comprehensive support for anonymous fields
- Fast (no-reflection) encoding/decoding of common maps and slices
- Code-generation for faster performance, supported in go 1.6+
- Support binary (e.g. messagepack, cbor) and text (e.g. json) formats
- Support indefinite-length formats to enable true streaming
(for formats which support it e.g. json, cbor)
- Support canonical encoding, where a value is ALWAYS encoded as same sequence of bytes.
This mostly applies to maps, where iteration order is non-deterministic.
- NIL in data stream decoded as zero value
- Never silently skip data when decoding.
User decides whether to return an error or silently skip data when keys or indexes
in the data stream do not map to fields in the struct.
- Detect and error when encoding a cyclic reference (instead of stack overflow shutdown)
- Encode/Decode from/to chan types (for iterative streaming support)
- Drop-in replacement for encoding/json. `json:` key in struct tag supported.
- Provides a RPC Server and Client Codec for net/rpc communication protocol.
- Handle unique idiosyncrasies of codecs e.g.
For messagepack, configure how ambiguities in handling raw bytes are resolved and
provide rpc server/client codec to support
msgpack-rpc protocol defined at:
https://github.com/msgpack-rpc/msgpack-rpc/blob/master/spec.md
# Extension Support
Users can register a function to handle the encoding or decoding of
their custom types.
There are no restrictions on what the custom type can be. Some examples:
type BisSet []int
type BitSet64 uint64
type UUID string
type MyStructWithUnexportedFields struct { a int; b bool; c []int; }
type GifImage struct { ... }
As an illustration, MyStructWithUnexportedFields would normally be
encoded as an empty map because it has no exported fields, while UUID
would be encoded as a string. However, with extension support, you can
encode any of these however you like.
There is also seamless support provided for registering an extension (with a tag)
but letting the encoding mechanism default to the standard way.
# Custom Encoding and Decoding
This package maintains symmetry in the encoding and decoding halfs.
We determine how to encode or decode by walking this decision tree
- is there an extension registered for the type?
- is type a codec.Selfer?
- is format binary, and is type a encoding.BinaryMarshaler and BinaryUnmarshaler?
- is format specifically json, and is type a encoding/json.Marshaler and Unmarshaler?
- is format text-based, and type an encoding.TextMarshaler and TextUnmarshaler?
- else we use a pair of functions based on the "kind" of the type e.g. map, slice, int64, etc
This symmetry is important to reduce chances of issues happening because the
encoding and decoding sides are out of sync e.g. decoded via very specific
encoding.TextUnmarshaler but encoded via kind-specific generalized mode.
Consequently, if a type only defines one-half of the symmetry
(e.g. it implements UnmarshalJSON() but not MarshalJSON() ),
then that type doesn't satisfy the check and we will continue walking down the
decision tree.
# RPC
RPC Client and Server Codecs are implemented, so the codecs can be used
with the standard net/rpc package.
# Usage
The Handle is SAFE for concurrent READ, but NOT SAFE for concurrent modification.
The Encoder and Decoder are NOT safe for concurrent use.
Consequently, the usage model is basically:
- Create and initialize the Handle before any use.
Once created, DO NOT modify it.
- Multiple Encoders or Decoders can now use the Handle concurrently.
They only read information off the Handle (never write).
- However, each Encoder or Decoder MUST not be used concurrently
- To re-use an Encoder/Decoder, call Reset(...) on it first.
This allows you use state maintained on the Encoder/Decoder.
Sample usage model:
// create and configure Handle
var (
bh codec.BincHandle
mh codec.MsgpackHandle
ch codec.CborHandle
)
mh.MapType = reflect.TypeOf(map[string]interface{}(nil))
// configure extensions
// e.g. for msgpack, define functions and enable Time support for tag 1
// mh.SetExt(reflect.TypeOf(time.Time{}), 1, myExt)
// create and use decoder/encoder
var (
r io.Reader
w io.Writer
b []byte
h = &bh // or mh to use msgpack
)
dec = codec.NewDecoder(r, h)
dec = codec.NewDecoderBytes(b, h)
err = dec.Decode(&v)
enc = codec.NewEncoder(w, h)
enc = codec.NewEncoderBytes(&b, h)
err = enc.Encode(v)
//RPC Server
go func() {
for {
conn, err := listener.Accept()
rpcCodec := codec.GoRpc.ServerCodec(conn, h)
//OR rpcCodec := codec.MsgpackSpecRpc.ServerCodec(conn, h)
rpc.ServeCodec(rpcCodec)
}
}()
//RPC Communication (client side)
conn, err = net.Dial("tcp", "localhost:5555")
rpcCodec := codec.GoRpc.ClientCodec(conn, h)
//OR rpcCodec := codec.MsgpackSpecRpc.ClientCodec(conn, h)
client := rpc.NewClientWithCodec(rpcCodec)
# Running Tests
To run tests, use the following:
go test
To run the full suite of tests, use the following:
go test -tags alltests -run Suite
You can run the tag 'codec.safe' to run tests or build in safe mode. e.g.
go test -tags codec.safe -run Json
go test -tags "alltests codec.safe" -run Suite
Running Benchmarks
cd bench
go test -bench . -benchmem -benchtime 1s
Please see http://github.com/ugorji/go-codec-bench .
# Caveats
Struct fields matching the following are ignored during encoding and decoding
- struct tag value set to -
- func, complex numbers, unsafe pointers
- unexported and not embedded
- unexported and embedded and not struct kind
- unexported and embedded pointers (from go1.10)
Every other field in a struct will be encoded/decoded.
Embedded fields are encoded as if they exist in the top-level struct,
with some caveats. See Encode documentation.
*/
package codec
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ugorji/go/codec/decode.go | vendor/github.com/ugorji/go/codec/decode.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
package codec
import (
"encoding"
"errors"
"io"
"math"
"reflect"
"strconv"
"time"
)
const msgBadDesc = "unrecognized descriptor byte"
const (
decDefMaxDepth = 1024 // maximum depth
decDefChanCap = 64 // should be large, as cap cannot be expanded
decScratchByteArrayLen = (8 + 2 + 2 + 1) * 8 // around cacheLineSize ie ~64, depending on Decoder size
// MARKER: massage decScratchByteArrayLen to ensure xxxDecDriver structs fit within cacheLine*N
// decFailNonEmptyIntf configures whether we error
// when decoding naked into a non-empty interface.
//
// Typically, we cannot decode non-nil stream value into
// nil interface with methods (e.g. io.Reader).
// However, in some scenarios, this should be allowed:
// - MapType
// - SliceType
// - Extensions
//
// Consequently, we should relax this. Put it behind a const flag for now.
decFailNonEmptyIntf = false
// decUseTransient says that we should not use the transient optimization.
//
// There's potential for GC corruption or memory overwrites if transient isn't
// used carefully, so this flag helps turn it off quickly if needed.
//
// Use it everywhere needed so we can completely remove unused code blocks.
decUseTransient = true
)
var (
errNeedMapOrArrayDecodeToStruct = errors.New("only encoded map or array can decode into struct")
errCannotDecodeIntoNil = errors.New("cannot decode into nil")
errExpandSliceCannotChange = errors.New("expand slice: cannot change")
errDecoderNotInitialized = errors.New("Decoder not initialized")
errDecUnreadByteNothingToRead = errors.New("cannot unread - nothing has been read")
errDecUnreadByteLastByteNotRead = errors.New("cannot unread - last byte has not been read")
errDecUnreadByteUnknown = errors.New("cannot unread - reason unknown")
errMaxDepthExceeded = errors.New("maximum decoding depth exceeded")
)
// decByteState tracks where the []byte returned by the last call
// to DecodeBytes or DecodeStringAsByte came from
type decByteState uint8
const (
decByteStateNone decByteState = iota
decByteStateZerocopy // view into []byte that we are decoding from
decByteStateReuseBuf // view into transient buffer used internally by decDriver
// decByteStateNewAlloc
)
type decNotDecodeableReason uint8
const (
decNotDecodeableReasonUnknown decNotDecodeableReason = iota
decNotDecodeableReasonBadKind
decNotDecodeableReasonNonAddrValue
decNotDecodeableReasonNilReference
)
type decDriver interface {
// this will check if the next token is a break.
CheckBreak() bool
// TryNil tries to decode as nil.
// If a nil is in the stream, it consumes it and returns true.
//
// Note: if TryNil returns true, that must be handled.
TryNil() bool
// ContainerType returns one of: Bytes, String, Nil, Slice or Map.
//
// Return unSet if not known.
//
// Note: Implementations MUST fully consume sentinel container types, specifically Nil.
ContainerType() (vt valueType)
// DecodeNaked will decode primitives (number, bool, string, []byte) and RawExt.
// For maps and arrays, it will not do the decoding in-band, but will signal
// the decoder, so that is done later, by setting the fauxUnion.valueType field.
//
// Note: Numbers are decoded as int64, uint64, float64 only (no smaller sized number types).
// for extensions, DecodeNaked must read the tag and the []byte if it exists.
// if the []byte is not read, then kInterfaceNaked will treat it as a Handle
// that stores the subsequent value in-band, and complete reading the RawExt.
//
// extensions should also use readx to decode them, for efficiency.
// kInterface will extract the detached byte slice if it has to pass it outside its realm.
DecodeNaked()
DecodeInt64() (i int64)
DecodeUint64() (ui uint64)
DecodeFloat64() (f float64)
DecodeBool() (b bool)
// DecodeStringAsBytes returns the bytes representing a string.
// It will return a view into scratch buffer or input []byte (if applicable).
//
// Note: This can also decode symbols, if supported.
//
// Users should consume it right away and not store it for later use.
DecodeStringAsBytes() (v []byte)
// DecodeBytes returns the bytes representing a binary value.
// It will return a view into scratch buffer or input []byte (if applicable).
//
// All implementations must honor the contract below:
// if ZeroCopy and applicable, return a view into input []byte we are decoding from
// else if in == nil, return a view into scratch buffer
// else append decoded value to in[:0] and return that
// (this can be simulated by passing []byte{} as in parameter)
//
// Implementations must also update Decoder.decByteState on each call to
// DecodeBytes or DecodeStringAsBytes. Some callers may check that and work appropriately.
//
// Note: DecodeBytes may decode past the length of the passed byte slice, up to the cap.
// Consequently, it is ok to pass a zero-len slice to DecodeBytes, as the returned
// byte slice will have the appropriate length.
DecodeBytes(in []byte) (out []byte)
// DecodeBytes(bs []byte, isstring, zerocopy bool) (bsOut []byte)
// DecodeExt will decode into a *RawExt or into an extension.
DecodeExt(v interface{}, basetype reflect.Type, xtag uint64, ext Ext)
// decodeExt(verifyTag bool, tag byte) (xtag byte, xbs []byte)
DecodeTime() (t time.Time)
// ReadArrayStart will return the length of the array.
// If the format doesn't prefix the length, it returns containerLenUnknown.
// If the expected array was a nil in the stream, it returns containerLenNil.
ReadArrayStart() int
// ReadMapStart will return the length of the array.
// If the format doesn't prefix the length, it returns containerLenUnknown.
// If the expected array was a nil in the stream, it returns containerLenNil.
ReadMapStart() int
reset()
// atEndOfDecode()
// nextValueBytes will return the bytes representing the next value in the stream.
//
// if start is nil, then treat it as a request to discard the next set of bytes,
// and the return response does not matter.
// Typically, this means that the returned []byte is nil/empty/undefined.
//
// Optimize for decoding from a []byte, where the nextValueBytes will just be a sub-slice
// of the input slice. Callers that need to use this to not be a view into the input bytes
// should handle it appropriately.
nextValueBytes(start []byte) []byte
// descBd will describe the token descriptor that signifies what type was decoded
descBd() string
decoder() *Decoder
driverStateManager
decNegintPosintFloatNumber
}
type decDriverContainerTracker interface {
ReadArrayElem()
ReadMapElemKey()
ReadMapElemValue()
ReadArrayEnd()
ReadMapEnd()
}
type decNegintPosintFloatNumber interface {
decInteger() (ui uint64, neg, ok bool)
decFloat() (f float64, ok bool)
}
type decDriverNoopNumberHelper struct{}
func (x decDriverNoopNumberHelper) decInteger() (ui uint64, neg, ok bool) {
panic("decInteger unsupported")
}
func (x decDriverNoopNumberHelper) decFloat() (f float64, ok bool) { panic("decFloat unsupported") }
type decDriverNoopContainerReader struct{}
// func (x decDriverNoopContainerReader) ReadArrayStart() (v int) { panic("ReadArrayStart unsupported") }
// func (x decDriverNoopContainerReader) ReadMapStart() (v int) { panic("ReadMapStart unsupported") }
func (x decDriverNoopContainerReader) ReadArrayEnd() {}
func (x decDriverNoopContainerReader) ReadMapEnd() {}
func (x decDriverNoopContainerReader) CheckBreak() (v bool) { return }
// DecodeOptions captures configuration options during decode.
type DecodeOptions struct {
// MapType specifies type to use during schema-less decoding of a map in the stream.
// If nil (unset), we default to map[string]interface{} iff json handle and MapKeyAsString=true,
// else map[interface{}]interface{}.
MapType reflect.Type
// SliceType specifies type to use during schema-less decoding of an array in the stream.
// If nil (unset), we default to []interface{} for all formats.
SliceType reflect.Type
// MaxInitLen defines the maxinum initial length that we "make" a collection
// (string, slice, map, chan). If 0 or negative, we default to a sensible value
// based on the size of an element in the collection.
//
// For example, when decoding, a stream may say that it has 2^64 elements.
// We should not auto-matically provision a slice of that size, to prevent Out-Of-Memory crash.
// Instead, we provision up to MaxInitLen, fill that up, and start appending after that.
MaxInitLen int
// ReaderBufferSize is the size of the buffer used when reading.
//
// if > 0, we use a smart buffer internally for performance purposes.
ReaderBufferSize int
// MaxDepth defines the maximum depth when decoding nested
// maps and slices. If 0 or negative, we default to a suitably large number (currently 1024).
MaxDepth int16
// If ErrorIfNoField, return an error when decoding a map
// from a codec stream into a struct, and no matching struct field is found.
ErrorIfNoField bool
// If ErrorIfNoArrayExpand, return an error when decoding a slice/array that cannot be expanded.
// For example, the stream contains an array of 8 items, but you are decoding into a [4]T array,
// or you are decoding into a slice of length 4 which is non-addressable (and so cannot be set).
ErrorIfNoArrayExpand bool
// If SignedInteger, use the int64 during schema-less decoding of unsigned values (not uint64).
SignedInteger bool
// MapValueReset controls how we decode into a map value.
//
// By default, we MAY retrieve the mapping for a key, and then decode into that.
// However, especially with big maps, that retrieval may be expensive and unnecessary
// if the stream already contains all that is necessary to recreate the value.
//
// If true, we will never retrieve the previous mapping,
// but rather decode into a new value and set that in the map.
//
// If false, we will retrieve the previous mapping if necessary e.g.
// the previous mapping is a pointer, or is a struct or array with pre-set state,
// or is an interface.
MapValueReset bool
// SliceElementReset: on decoding a slice, reset the element to a zero value first.
//
// concern: if the slice already contained some garbage, we will decode into that garbage.
SliceElementReset bool
// InterfaceReset controls how we decode into an interface.
//
// By default, when we see a field that is an interface{...},
// or a map with interface{...} value, we will attempt decoding into the
// "contained" value.
//
// However, this prevents us from reading a string into an interface{}
// that formerly contained a number.
//
// If true, we will decode into a new "blank" value, and set that in the interface.
// If false, we will decode into whatever is contained in the interface.
InterfaceReset bool
// InternString controls interning of strings during decoding.
//
// Some handles, e.g. json, typically will read map keys as strings.
// If the set of keys are finite, it may help reduce allocation to
// look them up from a map (than to allocate them afresh).
//
// Note: Handles will be smart when using the intern functionality.
// Every string should not be interned.
// An excellent use-case for interning is struct field names,
// or map keys where key type is string.
InternString bool
// PreferArrayOverSlice controls whether to decode to an array or a slice.
//
// This only impacts decoding into a nil interface{}.
//
// Consequently, it has no effect on codecgen.
//
// *Note*: This only applies if using go1.5 and above,
// as it requires reflect.ArrayOf support which was absent before go1.5.
PreferArrayOverSlice bool
// DeleteOnNilMapValue controls how to decode a nil value in the stream.
//
// If true, we will delete the mapping of the key.
// Else, just set the mapping to the zero value of the type.
//
// Deprecated: This does NOTHING and is left behind for compiling compatibility.
// This change is necessitated because 'nil' in a stream now consistently
// means the zero value (ie reset the value to its zero state).
DeleteOnNilMapValue bool
// RawToString controls how raw bytes in a stream are decoded into a nil interface{}.
// By default, they are decoded as []byte, but can be decoded as string (if configured).
RawToString bool
// ZeroCopy controls whether decoded values of []byte or string type
// point into the input []byte parameter passed to a NewDecoderBytes/ResetBytes(...) call.
//
// To illustrate, if ZeroCopy and decoding from a []byte (not io.Writer),
// then a []byte or string in the output result may just be a slice of (point into)
// the input bytes.
//
// This optimization prevents unnecessary copying.
//
// However, it is made optional, as the caller MUST ensure that the input parameter []byte is
// not modified after the Decode() happens, as any changes are mirrored in the decoded result.
ZeroCopy bool
// PreferPointerForStructOrArray controls whether a struct or array
// is stored in a nil interface{}, or a pointer to it.
//
// This mostly impacts when we decode registered extensions.
PreferPointerForStructOrArray bool
// ValidateUnicode controls will cause decoding to fail if an expected unicode
// string is well-formed but include invalid codepoints.
//
// This could have a performance impact.
ValidateUnicode bool
}
// ----------------------------------------
func (d *Decoder) rawExt(f *codecFnInfo, rv reflect.Value) {
d.d.DecodeExt(rv2i(rv), f.ti.rt, 0, nil)
}
func (d *Decoder) ext(f *codecFnInfo, rv reflect.Value) {
d.d.DecodeExt(rv2i(rv), f.ti.rt, f.xfTag, f.xfFn)
}
func (d *Decoder) selferUnmarshal(f *codecFnInfo, rv reflect.Value) {
rv2i(rv).(Selfer).CodecDecodeSelf(d)
}
func (d *Decoder) binaryUnmarshal(f *codecFnInfo, rv reflect.Value) {
bm := rv2i(rv).(encoding.BinaryUnmarshaler)
xbs := d.d.DecodeBytes(nil)
fnerr := bm.UnmarshalBinary(xbs)
d.onerror(fnerr)
}
func (d *Decoder) textUnmarshal(f *codecFnInfo, rv reflect.Value) {
tm := rv2i(rv).(encoding.TextUnmarshaler)
fnerr := tm.UnmarshalText(d.d.DecodeStringAsBytes())
d.onerror(fnerr)
}
func (d *Decoder) jsonUnmarshal(f *codecFnInfo, rv reflect.Value) {
d.jsonUnmarshalV(rv2i(rv).(jsonUnmarshaler))
}
func (d *Decoder) jsonUnmarshalV(tm jsonUnmarshaler) {
// grab the bytes to be read, as UnmarshalJSON needs the full JSON so as to unmarshal it itself.
var bs0 = []byte{}
if !d.bytes {
bs0 = d.blist.get(256)
}
bs := d.d.nextValueBytes(bs0)
fnerr := tm.UnmarshalJSON(bs)
if !d.bytes {
d.blist.put(bs)
if !byteSliceSameData(bs0, bs) {
d.blist.put(bs0)
}
}
d.onerror(fnerr)
}
func (d *Decoder) kErr(f *codecFnInfo, rv reflect.Value) {
d.errorf("no decoding function defined for kind %v", rv.Kind())
}
func (d *Decoder) raw(f *codecFnInfo, rv reflect.Value) {
rvSetBytes(rv, d.rawBytes())
}
func (d *Decoder) kString(f *codecFnInfo, rv reflect.Value) {
rvSetString(rv, d.stringZC(d.d.DecodeStringAsBytes()))
}
func (d *Decoder) kBool(f *codecFnInfo, rv reflect.Value) {
rvSetBool(rv, d.d.DecodeBool())
}
func (d *Decoder) kTime(f *codecFnInfo, rv reflect.Value) {
rvSetTime(rv, d.d.DecodeTime())
}
func (d *Decoder) kFloat32(f *codecFnInfo, rv reflect.Value) {
rvSetFloat32(rv, d.decodeFloat32())
}
func (d *Decoder) kFloat64(f *codecFnInfo, rv reflect.Value) {
rvSetFloat64(rv, d.d.DecodeFloat64())
}
func (d *Decoder) kComplex64(f *codecFnInfo, rv reflect.Value) {
rvSetComplex64(rv, complex(d.decodeFloat32(), 0))
}
func (d *Decoder) kComplex128(f *codecFnInfo, rv reflect.Value) {
rvSetComplex128(rv, complex(d.d.DecodeFloat64(), 0))
}
func (d *Decoder) kInt(f *codecFnInfo, rv reflect.Value) {
rvSetInt(rv, int(chkOvf.IntV(d.d.DecodeInt64(), intBitsize)))
}
func (d *Decoder) kInt8(f *codecFnInfo, rv reflect.Value) {
rvSetInt8(rv, int8(chkOvf.IntV(d.d.DecodeInt64(), 8)))
}
func (d *Decoder) kInt16(f *codecFnInfo, rv reflect.Value) {
rvSetInt16(rv, int16(chkOvf.IntV(d.d.DecodeInt64(), 16)))
}
func (d *Decoder) kInt32(f *codecFnInfo, rv reflect.Value) {
rvSetInt32(rv, int32(chkOvf.IntV(d.d.DecodeInt64(), 32)))
}
func (d *Decoder) kInt64(f *codecFnInfo, rv reflect.Value) {
rvSetInt64(rv, d.d.DecodeInt64())
}
func (d *Decoder) kUint(f *codecFnInfo, rv reflect.Value) {
rvSetUint(rv, uint(chkOvf.UintV(d.d.DecodeUint64(), uintBitsize)))
}
func (d *Decoder) kUintptr(f *codecFnInfo, rv reflect.Value) {
rvSetUintptr(rv, uintptr(chkOvf.UintV(d.d.DecodeUint64(), uintBitsize)))
}
func (d *Decoder) kUint8(f *codecFnInfo, rv reflect.Value) {
rvSetUint8(rv, uint8(chkOvf.UintV(d.d.DecodeUint64(), 8)))
}
func (d *Decoder) kUint16(f *codecFnInfo, rv reflect.Value) {
rvSetUint16(rv, uint16(chkOvf.UintV(d.d.DecodeUint64(), 16)))
}
func (d *Decoder) kUint32(f *codecFnInfo, rv reflect.Value) {
rvSetUint32(rv, uint32(chkOvf.UintV(d.d.DecodeUint64(), 32)))
}
func (d *Decoder) kUint64(f *codecFnInfo, rv reflect.Value) {
rvSetUint64(rv, d.d.DecodeUint64())
}
func (d *Decoder) kInterfaceNaked(f *codecFnInfo) (rvn reflect.Value) {
// nil interface:
// use some hieristics to decode it appropriately
// based on the detected next value in the stream.
n := d.naked()
d.d.DecodeNaked()
// We cannot decode non-nil stream value into nil interface with methods (e.g. io.Reader).
// Howver, it is possible that the user has ways to pass in a type for a given interface
// - MapType
// - SliceType
// - Extensions
//
// Consequently, we should relax this. Put it behind a const flag for now.
if decFailNonEmptyIntf && f.ti.numMeth > 0 {
d.errorf("cannot decode non-nil codec value into nil %v (%v methods)", f.ti.rt, f.ti.numMeth)
}
switch n.v {
case valueTypeMap:
mtid := d.mtid
if mtid == 0 {
if d.jsms { // if json, default to a map type with string keys
mtid = mapStrIntfTypId // for json performance
} else {
mtid = mapIntfIntfTypId
}
}
if mtid == mapStrIntfTypId {
var v2 map[string]interface{}
d.decode(&v2)
rvn = rv4iptr(&v2).Elem()
} else if mtid == mapIntfIntfTypId {
var v2 map[interface{}]interface{}
d.decode(&v2)
rvn = rv4iptr(&v2).Elem()
} else if d.mtr {
rvn = reflect.New(d.h.MapType)
d.decode(rv2i(rvn))
rvn = rvn.Elem()
} else {
rvn = rvZeroAddrK(d.h.MapType, reflect.Map)
d.decodeValue(rvn, nil)
}
case valueTypeArray:
if d.stid == 0 || d.stid == intfSliceTypId {
var v2 []interface{}
d.decode(&v2)
rvn = rv4iptr(&v2).Elem()
} else if d.str {
rvn = reflect.New(d.h.SliceType)
d.decode(rv2i(rvn))
rvn = rvn.Elem()
} else {
rvn = rvZeroAddrK(d.h.SliceType, reflect.Slice)
d.decodeValue(rvn, nil)
}
if reflectArrayOfSupported && d.h.PreferArrayOverSlice {
rvn = rvGetArray4Slice(rvn)
}
case valueTypeExt:
tag, bytes := n.u, n.l // calling decode below might taint the values
bfn := d.h.getExtForTag(tag)
var re = RawExt{Tag: tag}
if bytes == nil {
// it is one of the InterfaceExt ones: json and cbor.
// most likely cbor, as json decoding never reveals valueTypeExt (no tagging support)
if bfn == nil {
d.decode(&re.Value)
rvn = rv4iptr(&re).Elem()
} else {
if bfn.ext == SelfExt {
rvn = rvZeroAddrK(bfn.rt, bfn.rt.Kind())
d.decodeValue(rvn, d.h.fnNoExt(bfn.rt))
} else {
rvn = reflect.New(bfn.rt)
d.interfaceExtConvertAndDecode(rv2i(rvn), bfn.ext)
rvn = rvn.Elem()
}
}
} else {
// one of the BytesExt ones: binc, msgpack, simple
if bfn == nil {
re.setData(bytes, false)
rvn = rv4iptr(&re).Elem()
} else {
rvn = reflect.New(bfn.rt)
if bfn.ext == SelfExt {
d.sideDecode(rv2i(rvn), bfn.rt, bytes)
} else {
bfn.ext.ReadExt(rv2i(rvn), bytes)
}
rvn = rvn.Elem()
}
}
// if struct/array, directly store pointer into the interface
if d.h.PreferPointerForStructOrArray && rvn.CanAddr() {
if rk := rvn.Kind(); rk == reflect.Array || rk == reflect.Struct {
rvn = rvn.Addr()
}
}
case valueTypeNil:
// rvn = reflect.Zero(f.ti.rt)
// no-op
case valueTypeInt:
rvn = n.ri()
case valueTypeUint:
rvn = n.ru()
case valueTypeFloat:
rvn = n.rf()
case valueTypeBool:
rvn = n.rb()
case valueTypeString, valueTypeSymbol:
rvn = n.rs()
case valueTypeBytes:
rvn = n.rl()
case valueTypeTime:
rvn = n.rt()
default:
halt.errorf("kInterfaceNaked: unexpected valueType: %d", n.v)
}
return
}
func (d *Decoder) kInterface(f *codecFnInfo, rv reflect.Value) {
// Note: A consequence of how kInterface works, is that
// if an interface already contains something, we try
// to decode into what was there before.
// We do not replace with a generic value (as got from decodeNaked).
//
// every interface passed here MUST be settable.
//
// ensure you call rvSetIntf(...) before returning.
isnilrv := rvIsNil(rv)
var rvn reflect.Value
if d.h.InterfaceReset {
// check if mapping to a type: if so, initialize it and move on
rvn = d.h.intf2impl(f.ti.rtid)
if !rvn.IsValid() {
rvn = d.kInterfaceNaked(f)
if rvn.IsValid() {
rvSetIntf(rv, rvn)
} else if !isnilrv {
decSetNonNilRV2Zero4Intf(rv)
}
return
}
} else if isnilrv {
// check if mapping to a type: if so, initialize it and move on
rvn = d.h.intf2impl(f.ti.rtid)
if !rvn.IsValid() {
rvn = d.kInterfaceNaked(f)
if rvn.IsValid() {
rvSetIntf(rv, rvn)
}
return
}
} else {
// now we have a non-nil interface value, meaning it contains a type
rvn = rv.Elem()
}
// rvn is now a non-interface type
canDecode, _ := isDecodeable(rvn)
// Note: interface{} is settable, but underlying type may not be.
// Consequently, we MAY have to allocate a value (containing the underlying value),
// decode into it, and reset the interface to that new value.
if !canDecode {
rvn2 := d.oneShotAddrRV(rvn.Type(), rvn.Kind())
rvSetDirect(rvn2, rvn)
rvn = rvn2
}
d.decodeValue(rvn, nil)
rvSetIntf(rv, rvn)
}
func decStructFieldKeyNotString(dd decDriver, keyType valueType, b *[decScratchByteArrayLen]byte) (rvkencname []byte) {
if keyType == valueTypeInt {
rvkencname = strconv.AppendInt(b[:0], dd.DecodeInt64(), 10)
} else if keyType == valueTypeUint {
rvkencname = strconv.AppendUint(b[:0], dd.DecodeUint64(), 10)
} else if keyType == valueTypeFloat {
rvkencname = strconv.AppendFloat(b[:0], dd.DecodeFloat64(), 'f', -1, 64)
} else {
halt.errorf("invalid struct key type: %v", keyType)
}
return
}
func (d *Decoder) kStructField(si *structFieldInfo, rv reflect.Value) {
if d.d.TryNil() {
if rv = si.path.field(rv); rv.IsValid() {
decSetNonNilRV2Zero(rv)
}
return
}
d.decodeValueNoCheckNil(si.path.fieldAlloc(rv), nil)
}
func (d *Decoder) kStruct(f *codecFnInfo, rv reflect.Value) {
ctyp := d.d.ContainerType()
ti := f.ti
var mf MissingFielder
if ti.flagMissingFielder {
mf = rv2i(rv).(MissingFielder)
} else if ti.flagMissingFielderPtr {
mf = rv2i(rvAddr(rv, ti.ptr)).(MissingFielder)
}
if ctyp == valueTypeMap {
containerLen := d.mapStart(d.d.ReadMapStart())
if containerLen == 0 {
d.mapEnd()
return
}
hasLen := containerLen >= 0
var name2 []byte
if mf != nil {
var namearr2 [16]byte
name2 = namearr2[:0]
}
var rvkencname []byte
for j := 0; d.containerNext(j, containerLen, hasLen); j++ {
d.mapElemKey()
if ti.keyType == valueTypeString {
rvkencname = d.d.DecodeStringAsBytes()
} else {
rvkencname = decStructFieldKeyNotString(d.d, ti.keyType, &d.b)
}
d.mapElemValue()
if si := ti.siForEncName(rvkencname); si != nil {
d.kStructField(si, rv)
} else if mf != nil {
// store rvkencname in new []byte, as it previously shares Decoder.b, which is used in decode
name2 = append(name2[:0], rvkencname...)
var f interface{}
d.decode(&f)
if !mf.CodecMissingField(name2, f) && d.h.ErrorIfNoField {
d.errorf("no matching struct field when decoding stream map with key: %s ", stringView(name2))
}
} else {
d.structFieldNotFound(-1, stringView(rvkencname))
}
}
d.mapEnd()
} else if ctyp == valueTypeArray {
containerLen := d.arrayStart(d.d.ReadArrayStart())
if containerLen == 0 {
d.arrayEnd()
return
}
// Not much gain from doing it two ways for array.
// Arrays are not used as much for structs.
tisfi := ti.sfi.source()
hasLen := containerLen >= 0
// iterate all the items in the stream
// if mapped elem-wise to a field, handle it
// if more stream items than can be mapped, error it
for j := 0; d.containerNext(j, containerLen, hasLen); j++ {
d.arrayElem()
if j < len(tisfi) {
d.kStructField(tisfi[j], rv)
} else {
d.structFieldNotFound(j, "")
}
}
d.arrayEnd()
} else {
d.onerror(errNeedMapOrArrayDecodeToStruct)
}
}
func (d *Decoder) kSlice(f *codecFnInfo, rv reflect.Value) {
// A slice can be set from a map or array in stream.
// This way, the order can be kept (as order is lost with map).
// Note: rv is a slice type here - guaranteed
ti := f.ti
rvCanset := rv.CanSet()
ctyp := d.d.ContainerType()
if ctyp == valueTypeBytes || ctyp == valueTypeString {
// you can only decode bytes or string in the stream into a slice or array of bytes
if !(ti.rtid == uint8SliceTypId || ti.elemkind == uint8(reflect.Uint8)) {
d.errorf("bytes/string in stream must decode into slice/array of bytes, not %v", ti.rt)
}
rvbs := rvGetBytes(rv)
if !rvCanset {
// not addressable byte slice, so do not decode into it past the length
rvbs = rvbs[:len(rvbs):len(rvbs)]
}
bs2 := d.decodeBytesInto(rvbs)
// if !(len(bs2) == len(rvbs) && byteSliceSameData(rvbs, bs2)) {
if !(len(bs2) > 0 && len(bs2) == len(rvbs) && &bs2[0] == &rvbs[0]) {
if rvCanset {
rvSetBytes(rv, bs2)
} else if len(rvbs) > 0 && len(bs2) > 0 {
copy(rvbs, bs2)
}
}
return
}
slh, containerLenS := d.decSliceHelperStart() // only expects valueType(Array|Map) - never Nil
// an array can never return a nil slice. so no need to check f.array here.
if containerLenS == 0 {
if rvCanset {
if rvIsNil(rv) {
rvSetDirect(rv, rvSliceZeroCap(ti.rt))
} else {
rvSetSliceLen(rv, 0)
}
}
slh.End()
return
}
rtelem0Mut := !scalarBitset.isset(ti.elemkind)
rtelem := ti.elem
for k := reflect.Kind(ti.elemkind); k == reflect.Ptr; k = rtelem.Kind() {
rtelem = rtelem.Elem()
}
var fn *codecFn
var rvChanged bool
var rv0 = rv
var rv9 reflect.Value
rvlen := rvLenSlice(rv)
rvcap := rvCapSlice(rv)
hasLen := containerLenS > 0
if hasLen {
if containerLenS > rvcap {
oldRvlenGtZero := rvlen > 0
rvlen1 := decInferLen(containerLenS, d.h.MaxInitLen, int(ti.elemsize))
if rvlen1 == rvlen {
} else if rvlen1 <= rvcap {
if rvCanset {
rvlen = rvlen1
rvSetSliceLen(rv, rvlen)
}
} else if rvCanset { // rvlen1 > rvcap
rvlen = rvlen1
rv, rvCanset = rvMakeSlice(rv, f.ti, rvlen, rvlen)
rvcap = rvlen
rvChanged = !rvCanset
} else { // rvlen1 > rvcap && !canSet
d.errorf("cannot decode into non-settable slice")
}
if rvChanged && oldRvlenGtZero && rtelem0Mut {
rvCopySlice(rv, rv0, rtelem) // only copy up to length NOT cap i.e. rv0.Slice(0, rvcap)
}
} else if containerLenS != rvlen {
if rvCanset {
rvlen = containerLenS
rvSetSliceLen(rv, rvlen)
}
}
}
// consider creating new element once, and just decoding into it.
var elemReset = d.h.SliceElementReset
var j int
for ; d.containerNext(j, containerLenS, hasLen); j++ {
if j == 0 {
if rvIsNil(rv) { // means hasLen = false
if rvCanset {
rvlen = decInferLen(containerLenS, d.h.MaxInitLen, int(ti.elemsize))
rv, rvCanset = rvMakeSlice(rv, f.ti, rvlen, rvlen)
rvcap = rvlen
rvChanged = !rvCanset
} else {
d.errorf("cannot decode into non-settable slice")
}
}
if fn == nil {
fn = d.h.fn(rtelem)
}
}
// if indefinite, etc, then expand the slice if necessary
if j >= rvlen {
slh.ElemContainerState(j)
// expand the slice up to the cap.
// Note that we did, so we have to reset it later.
if rvlen < rvcap {
rvlen = rvcap
if rvCanset {
rvSetSliceLen(rv, rvlen)
} else if rvChanged {
rv = rvSlice(rv, rvlen)
} else {
d.onerror(errExpandSliceCannotChange)
}
} else {
if !(rvCanset || rvChanged) {
d.onerror(errExpandSliceCannotChange)
}
rv, rvcap, rvCanset = rvGrowSlice(rv, f.ti, rvcap, 1)
rvlen = rvcap
rvChanged = !rvCanset
}
} else {
slh.ElemContainerState(j)
}
rv9 = rvSliceIndex(rv, j, f.ti)
if elemReset {
rvSetZero(rv9)
}
d.decodeValue(rv9, fn)
}
if j < rvlen {
if rvCanset {
rvSetSliceLen(rv, j)
} else if rvChanged {
rv = rvSlice(rv, j)
}
// rvlen = j
} else if j == 0 && rvIsNil(rv) {
if rvCanset {
rv = rvSliceZeroCap(ti.rt)
rvCanset = false
rvChanged = true
}
}
slh.End()
if rvChanged { // infers rvCanset=true, so it can be reset
rvSetDirect(rv0, rv)
}
}
func (d *Decoder) kArray(f *codecFnInfo, rv reflect.Value) {
// An array can be set from a map or array in stream.
ctyp := d.d.ContainerType()
if handleBytesWithinKArray && (ctyp == valueTypeBytes || ctyp == valueTypeString) {
// you can only decode bytes or string in the stream into a slice or array of bytes
if f.ti.elemkind != uint8(reflect.Uint8) {
d.errorf("bytes/string in stream can decode into array of bytes, but not %v", f.ti.rt)
}
rvbs := rvGetArrayBytes(rv, nil)
bs2 := d.decodeBytesInto(rvbs)
if !byteSliceSameData(rvbs, bs2) && len(rvbs) > 0 && len(bs2) > 0 {
copy(rvbs, bs2)
}
return
}
slh, containerLenS := d.decSliceHelperStart() // only expects valueType(Array|Map) - never Nil
// an array can never return a nil slice. so no need to check f.array here.
if containerLenS == 0 {
slh.End()
return
}
rtelem := f.ti.elem
for k := reflect.Kind(f.ti.elemkind); k == reflect.Ptr; k = rtelem.Kind() {
rtelem = rtelem.Elem()
}
var fn *codecFn
var rv9 reflect.Value
rvlen := rv.Len() // same as cap
hasLen := containerLenS > 0
if hasLen && containerLenS > rvlen {
d.errorf("cannot decode into array with length: %v, less than container length: %v", rvlen, containerLenS)
}
// consider creating new element once, and just decoding into it.
var elemReset = d.h.SliceElementReset
for j := 0; d.containerNext(j, containerLenS, hasLen); j++ {
// note that you cannot expand the array if indefinite and we go past array length
if j >= rvlen {
slh.arrayCannotExpand(hasLen, rvlen, j, containerLenS)
return
}
slh.ElemContainerState(j)
rv9 = rvArrayIndex(rv, j, f.ti)
if elemReset {
rvSetZero(rv9)
}
if fn == nil {
fn = d.h.fn(rtelem)
}
d.decodeValue(rv9, fn)
}
slh.End()
}
func (d *Decoder) kChan(f *codecFnInfo, rv reflect.Value) {
// A slice can be set from a map or array in stream.
// This way, the order can be kept (as order is lost with map).
ti := f.ti
if ti.chandir&uint8(reflect.SendDir) == 0 {
d.errorf("receive-only channel cannot be decoded")
}
ctyp := d.d.ContainerType()
if ctyp == valueTypeBytes || ctyp == valueTypeString {
// you can only decode bytes or string in the stream into a slice or array of bytes
if !(ti.rtid == uint8SliceTypId || ti.elemkind == uint8(reflect.Uint8)) {
d.errorf("bytes/string in stream must decode into slice/array of bytes, not %v", ti.rt)
}
bs2 := d.d.DecodeBytes(nil)
irv := rv2i(rv)
ch, ok := irv.(chan<- byte)
if !ok {
ch = irv.(chan byte)
}
for _, b := range bs2 {
ch <- b
}
return
}
var rvCanset = rv.CanSet()
// only expects valueType(Array|Map - nil handled above)
slh, containerLenS := d.decSliceHelperStart()
// an array can never return a nil slice. so no need to check f.array here.
if containerLenS == 0 {
if rvCanset && rvIsNil(rv) {
rvSetDirect(rv, reflect.MakeChan(ti.rt, 0))
}
slh.End()
return
}
rtelem := ti.elem
useTransient := decUseTransient && ti.elemkind != byte(reflect.Ptr) && ti.tielem.flagCanTransient
for k := reflect.Kind(ti.elemkind); k == reflect.Ptr; k = rtelem.Kind() {
rtelem = rtelem.Elem()
}
var fn *codecFn
var rvChanged bool
var rv0 = rv
var rv9 reflect.Value
var rvlen int // = rv.Len()
hasLen := containerLenS > 0
for j := 0; d.containerNext(j, containerLenS, hasLen); j++ {
if j == 0 {
if rvIsNil(rv) {
if hasLen {
rvlen = decInferLen(containerLenS, d.h.MaxInitLen, int(ti.elemsize))
} else {
rvlen = decDefChanCap
}
if rvCanset {
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | true |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ugorji/go/codec/goversion_makemap_lt_go110.go | vendor/github.com/ugorji/go/codec/goversion_makemap_lt_go110.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
//go:build !go1.10
// +build !go1.10
package codec
import "reflect"
func makeMapReflect(t reflect.Type, size int) reflect.Value {
return reflect.MakeMap(t)
}
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
kubev2v/forklift | https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/vendor/github.com/ugorji/go/codec/goversion_unexportedembeddedptr_gte_go110.go | vendor/github.com/ugorji/go/codec/goversion_unexportedembeddedptr_gte_go110.go | // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.
//go:build go1.10
// +build go1.10
package codec
const allowSetUnexportedEmbeddedPtr = false
| go | Apache-2.0 | b3b4703e958c25d54c4d48138d9e80ae32fadac3 | 2026-01-07T09:44:30.792320Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.