code
stringlengths 12
335k
| docstring
stringlengths 20
20.8k
| func_name
stringlengths 1
105
| language
stringclasses 1
value | repo
stringclasses 498
values | path
stringlengths 5
172
| url
stringlengths 43
235
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
func RegisterConverter(fromVersion string, toVersions []string, convertFn ConvertFn) {
// Make sure there is no converter already registered for these
// from and to versions
for _, v := range toVersions {
if findConverter(fromVersion, v) != nil {
panic(fmt.Sprintf("converter already registered for %s to %s",
fromVersion, v))
}
}
converters = append(converters, &converter{
fromVersion: fromVersion,
toVersions: toVersions,
convertFn: convertFn,
})
} | RegisterConverter registers a CNI Result converter. SHOULD NOT BE CALLED
EXCEPT FROM CNI ITSELF. | RegisterConverter | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/pkg/types/internal/convert.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/pkg/types/internal/convert.go | Apache-2.0 |
func ValidateContainerID(containerID string) *types.Error {
if containerID == "" {
return types.NewError(types.ErrUnknownContainer, "missing containerID", "")
}
if !cniReg.MatchString(containerID) {
return types.NewError(types.ErrInvalidEnvironmentVariables, "invalid characters in containerID", containerID)
}
return nil
} | ValidateContainerID will validate that the supplied containerID is not empty does not contain invalid characters | ValidateContainerID | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/pkg/utils/utils.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/pkg/utils/utils.go | Apache-2.0 |
func ValidateNetworkName(networkName string) *types.Error {
if networkName == "" {
return types.NewError(types.ErrInvalidNetworkConfig, "missing network name:", "")
}
if !cniReg.MatchString(networkName) {
return types.NewError(types.ErrInvalidNetworkConfig, "invalid characters found in network name", networkName)
}
return nil
} | ValidateNetworkName will validate that the supplied networkName does not contain invalid characters | ValidateNetworkName | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/pkg/utils/utils.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/pkg/utils/utils.go | Apache-2.0 |
func ValidateInterfaceName(ifName string) *types.Error {
if len(ifName) == 0 {
return types.NewError(types.ErrInvalidEnvironmentVariables, "interface name is empty", "")
}
if len(ifName) > maxInterfaceNameLength {
return types.NewError(types.ErrInvalidEnvironmentVariables, "interface name is too long", fmt.Sprintf("interface name should be less than %d characters", maxInterfaceNameLength+1))
}
if ifName == "." || ifName == ".." {
return types.NewError(types.ErrInvalidEnvironmentVariables, "interface name is . or ..", "")
}
for _, r := range bytes.Runes([]byte(ifName)) {
if r == '/' || r == ':' || unicode.IsSpace(r) {
return types.NewError(types.ErrInvalidEnvironmentVariables, "interface name contains / or : or whitespace characters", "")
}
}
return nil
} | ValidateInterfaceName will validate the interface name based on the four rules below
1. The name must not be empty
2. The name must be less than 16 characters
3. The name must not be "." or ".."
4. The name must not contain / or : or any whitespace characters
ref to https://github.com/torvalds/linux/blob/master/net/core/dev.c#L1024 | ValidateInterfaceName | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/pkg/utils/utils.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/pkg/utils/utils.go | Apache-2.0 |
func NetworkPluginConfFromBytes(pluginConfBytes []byte) (*PluginConfig, error) {
// TODO why are we creating a struct that holds both the byte representation and the deserialized
// representation, and returning that, instead of just returning the deserialized representation?
conf := &PluginConfig{Bytes: pluginConfBytes, Network: &types.PluginConf{}}
if err := json.Unmarshal(pluginConfBytes, conf.Network); err != nil {
return nil, fmt.Errorf("error parsing configuration: %w", err)
}
if conf.Network.Type == "" {
return nil, fmt.Errorf("error parsing configuration: missing 'type'")
}
return conf, nil
} | This will not validate that the plugins actually belong to the netconfig by ensuring
that they are loaded from a directory named after the networkName, relative to the network config.
Since here we are just accepting raw bytes, the caller is responsible for ensuring that the plugin
config provided here actually "belongs" to the networkconfig in question. | NetworkPluginConfFromBytes | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/conf.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/conf.go | Apache-2.0 |
func NetworkPluginConfsFromFiles(networkConfPath, networkName string) ([]*PluginConfig, error) {
var pConfs []*PluginConfig
pluginConfPath := filepath.Join(networkConfPath, networkName)
pluginConfFiles, err := ConfFiles(pluginConfPath, []string{".conf"})
if err != nil {
return nil, fmt.Errorf("failed to read plugin config files in %s: %w", pluginConfPath, err)
}
for _, pluginConfFile := range pluginConfFiles {
pluginConfBytes, err := os.ReadFile(pluginConfFile)
if err != nil {
return nil, fmt.Errorf("error reading %s: %w", pluginConfFile, err)
}
pluginConf, err := NetworkPluginConfFromBytes(pluginConfBytes)
if err != nil {
return nil, err
}
pConfs = append(pConfs, pluginConf)
}
return pConfs, nil
} | Given a path to a directory containing a network configuration, and the name of a network,
loads all plugin definitions found at path `networkConfPath/networkName/*.conf` | NetworkPluginConfsFromFiles | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/conf.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/conf.go | Apache-2.0 |
func ConfFromBytes(bytes []byte) (*NetworkConfig, error) {
return NetworkPluginConfFromBytes(bytes)
} | Deprecated: This file format is no longer supported, use NetworkConfXXX and NetworkPluginXXX functions | ConfFromBytes | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/conf.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/conf.go | Apache-2.0 |
func ConfFromFile(filename string) (*NetworkConfig, error) {
bytes, err := os.ReadFile(filename)
if err != nil {
return nil, fmt.Errorf("error reading %s: %w", filename, err)
}
return ConfFromBytes(bytes)
} | Deprecated: This file format is no longer supported, use NetworkConfXXX and NetworkPluginXXX functions | ConfFromFile | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/conf.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/conf.go | Apache-2.0 |
func ConfFiles(dir string, extensions []string) ([]string, error) {
// In part, adapted from rkt/networking/podenv.go#listFiles
files, err := os.ReadDir(dir)
switch {
case err == nil: // break
case os.IsNotExist(err):
// If folder not there, return no error - only return an
// error if we cannot read contents or there are no contents.
return nil, nil
default:
return nil, err
}
confFiles := []string{}
for _, f := range files {
if f.IsDir() {
continue
}
fileExt := filepath.Ext(f.Name())
for _, ext := range extensions {
if fileExt == ext {
confFiles = append(confFiles, filepath.Join(dir, f.Name()))
}
}
}
return confFiles, nil
} | ConfFiles simply returns a slice of all files in the provided directory
with extensions matching the provided set. | ConfFiles | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/conf.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/conf.go | Apache-2.0 |
func LoadConf(dir, name string) (*NetworkConfig, error) {
files, err := ConfFiles(dir, []string{".conf", ".json"})
switch {
case err != nil:
return nil, err
case len(files) == 0:
return nil, NoConfigsFoundError{Dir: dir}
}
sort.Strings(files)
for _, confFile := range files {
conf, err := ConfFromFile(confFile)
if err != nil {
return nil, err
}
if conf.Network.Name == name {
return conf, nil
}
}
return nil, NotFoundError{dir, name}
} | Deprecated: This file format is no longer supported, use NetworkConfXXX and NetworkPluginXXX functions | LoadConf | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/conf.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/conf.go | Apache-2.0 |
func LoadNetworkConf(dir, name string) (*NetworkConfigList, error) {
// TODO this .conflist/.conf extension thing is confusing and inexact
// for implementors. We should pick one extension for everything and stick with it.
files, err := ConfFiles(dir, []string{".conflist"})
if err != nil {
return nil, err
}
sort.Strings(files)
for _, confFile := range files {
conf, err := NetworkConfFromFile(confFile)
if err != nil {
return nil, err
}
if conf.Name == name {
return conf, nil
}
}
// Deprecated: Try and load a network configuration file (instead of list)
// from the same name, then upconvert.
singleConf, err := LoadConf(dir, name)
if err != nil {
// A little extra logic so the error makes sense
var ncfErr NoConfigsFoundError
if len(files) != 0 && errors.As(err, &ncfErr) {
// Config lists found but no config files found
return nil, NotFoundError{dir, name}
}
return nil, err
}
return ConfListFromConf(singleConf)
} | LoadNetworkConf looks at all the network configs in a given dir,
loads and parses them all, and returns the first one with an extension of `.conf`
that matches the provided network name predicate. | LoadNetworkConf | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/conf.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/conf.go | Apache-2.0 |
func InjectConf(original *PluginConfig, newValues map[string]interface{}) (*PluginConfig, error) {
config := make(map[string]interface{})
err := json.Unmarshal(original.Bytes, &config)
if err != nil {
return nil, fmt.Errorf("unmarshal existing network bytes: %w", err)
}
for key, value := range newValues {
if key == "" {
return nil, fmt.Errorf("keys cannot be empty")
}
if value == nil {
return nil, fmt.Errorf("key '%s' value must not be nil", key)
}
config[key] = value
}
newBytes, err := json.Marshal(config)
if err != nil {
return nil, err
}
return NetworkPluginConfFromBytes(newBytes)
} | InjectConf takes a PluginConfig and inserts additional values into it, ensuring the result is serializable. | InjectConf | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/conf.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/conf.go | Apache-2.0 |
func ConfListFromConf(original *PluginConfig) (*NetworkConfigList, error) {
// Re-deserialize the config's json, then make a raw map configlist.
// This may seem a bit strange, but it's to make the Bytes fields
// actually make sense. Otherwise, the generated json is littered with
// golang default values.
rawConfig := make(map[string]interface{})
if err := json.Unmarshal(original.Bytes, &rawConfig); err != nil {
return nil, err
}
rawConfigList := map[string]interface{}{
"name": original.Network.Name,
"cniVersion": original.Network.CNIVersion,
"plugins": []interface{}{rawConfig},
}
b, err := json.Marshal(rawConfigList)
if err != nil {
return nil, err
}
return ConfListFromBytes(b)
} | ConfListFromConf "upconverts" a network config in to a NetworkConfigList,
with the single network as the only entry in the list.
Deprecated: Non-conflist file formats are unsupported, use NetworkConfXXX and NetworkPluginXXX functions | ConfListFromConf | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/conf.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/conf.go | Apache-2.0 |
func NewCNIConfig(path []string, exec invoke.Exec) *CNIConfig {
return NewCNIConfigWithCacheDir(path, "", exec)
} | NewCNIConfig returns a new CNIConfig object that will search for plugins
in the given paths and use the given exec interface to run those plugins,
or if the exec interface is not given, will use a default exec handler. | NewCNIConfig | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/api.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/api.go | Apache-2.0 |
func NewCNIConfigWithCacheDir(path []string, cacheDir string, exec invoke.Exec) *CNIConfig {
return &CNIConfig{
Path: path,
cacheDir: cacheDir,
exec: exec,
}
} | NewCNIConfigWithCacheDir returns a new CNIConfig object that will search for plugins
in the given paths use the given exec interface to run those plugins,
or if the exec interface is not given, will use a default exec handler.
The given cache directory will be used for temporary data storage when needed. | NewCNIConfigWithCacheDir | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/api.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/api.go | Apache-2.0 |
func injectRuntimeConfig(orig *PluginConfig, rt *RuntimeConf) (*PluginConfig, error) {
var err error
rc := make(map[string]interface{})
for capability, supported := range orig.Network.Capabilities {
if !supported {
continue
}
if data, ok := rt.CapabilityArgs[capability]; ok {
rc[capability] = data
}
}
if len(rc) > 0 {
orig, err = InjectConf(orig, map[string]interface{}{"runtimeConfig": rc})
if err != nil {
return nil, err
}
}
return orig, nil
} | This function takes a libcni RuntimeConf structure and injects values into
a "runtimeConfig" dictionary in the CNI network configuration JSON that
will be passed to the plugin on stdin.
Only "capabilities arguments" passed by the runtime are currently injected.
These capabilities arguments are filtered through the plugin's advertised
capabilities from its config JSON, and any keys in the CapabilityArgs
matching plugin capabilities are added to the "runtimeConfig" dictionary
sent to the plugin via JSON on stdin. For example, if the plugin's
capabilities include "portMappings", and the CapabilityArgs map includes a
"portMappings" key, that key and its value are added to the "runtimeConfig"
dictionary to be passed to the plugin's stdin. | injectRuntimeConfig | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/api.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/api.go | Apache-2.0 |
func (c *CNIConfig) ensureExec() invoke.Exec {
if c.exec == nil {
c.exec = &invoke.DefaultExec{
RawExec: &invoke.RawExec{Stderr: os.Stderr},
PluginDecoder: version.PluginDecoder{},
}
}
return c.exec
} | ensure we have a usable exec if the CNIConfig was not given one | ensureExec | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/api.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/api.go | Apache-2.0 |
func (c *CNIConfig) getCacheDir(rt *RuntimeConf) string {
if c.cacheDir != "" {
return c.cacheDir
}
if rt.CacheDir != "" {
return rt.CacheDir
}
return CacheDir
} | getCacheDir returns the cache directory in this order:
1) global cacheDir from CNIConfig object
2) deprecated cacheDir from RuntimeConf object
3) fall back to default cache directory | getCacheDir | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/api.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/api.go | Apache-2.0 |
func (c *CNIConfig) GetNetworkListCachedResult(list *NetworkConfigList, rt *RuntimeConf) (types.Result, error) {
return c.getCachedResult(list.Name, list.CNIVersion, rt)
} | GetNetworkListCachedResult returns the cached Result of the previous
AddNetworkList() operation for a network list, or an error. | GetNetworkListCachedResult | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/api.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/api.go | Apache-2.0 |
func (c *CNIConfig) GetNetworkCachedResult(net *PluginConfig, rt *RuntimeConf) (types.Result, error) {
return c.getCachedResult(net.Network.Name, net.Network.CNIVersion, rt)
} | GetNetworkCachedResult returns the cached Result of the previous
AddNetwork() operation for a network, or an error. | GetNetworkCachedResult | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/api.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/api.go | Apache-2.0 |
func (c *CNIConfig) GetNetworkListCachedConfig(list *NetworkConfigList, rt *RuntimeConf) ([]byte, *RuntimeConf, error) {
return c.getCachedConfig(list.Name, rt)
} | GetNetworkListCachedConfig copies the input RuntimeConf to output
RuntimeConf with fields updated with info from the cached Config. | GetNetworkListCachedConfig | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/api.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/api.go | Apache-2.0 |
func (c *CNIConfig) GetNetworkCachedConfig(net *PluginConfig, rt *RuntimeConf) ([]byte, *RuntimeConf, error) {
return c.getCachedConfig(net.Network.Name, rt)
} | GetNetworkCachedConfig copies the input RuntimeConf to output
RuntimeConf with fields updated with info from the cached Config. | GetNetworkCachedConfig | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/api.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/api.go | Apache-2.0 |
func (c *CNIConfig) GetCachedAttachments(containerID string) ([]*NetworkAttachment, error) {
dirPath := filepath.Join(c.getCacheDir(&RuntimeConf{}), "results")
entries, err := os.ReadDir(dirPath)
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
fileNames := make([]string, 0, len(entries))
for _, e := range entries {
fileNames = append(fileNames, e.Name())
}
sort.Strings(fileNames)
attachments := []*NetworkAttachment{}
for _, fname := range fileNames {
if len(containerID) > 0 {
part := fmt.Sprintf("-%s-", containerID)
pos := strings.Index(fname, part)
if pos <= 0 || pos+len(part) >= len(fname) {
continue
}
}
cacheFile := filepath.Join(dirPath, fname)
bytes, err := os.ReadFile(cacheFile)
if err != nil {
continue
}
cachedInfo := cachedInfo{}
if err := json.Unmarshal(bytes, &cachedInfo); err != nil {
continue
}
if cachedInfo.Kind != CNICacheV1 {
continue
}
if len(containerID) > 0 && cachedInfo.ContainerID != containerID {
continue
}
if cachedInfo.IfName == "" || cachedInfo.NetworkName == "" {
continue
}
attachments = append(attachments, &NetworkAttachment{
ContainerID: cachedInfo.ContainerID,
Network: cachedInfo.NetworkName,
IfName: cachedInfo.IfName,
Config: cachedInfo.Config,
NetNS: cachedInfo.NetNS,
CniArgs: cachedInfo.CniArgs,
CapabilityArgs: cachedInfo.CapabilityArgs,
})
}
return attachments, nil
} | GetCachedAttachments returns a list of network attachments from the cache.
The returned list will be filtered by the containerID if the value is not empty. | GetCachedAttachments | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/api.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/api.go | Apache-2.0 |
func (c *CNIConfig) AddNetworkList(ctx context.Context, list *NetworkConfigList, rt *RuntimeConf) (types.Result, error) {
var err error
var result types.Result
for _, net := range list.Plugins {
result, err = c.addNetwork(ctx, list.Name, list.CNIVersion, net, result, rt)
if err != nil {
return nil, fmt.Errorf("plugin %s failed (add): %w", pluginDescription(net.Network), err)
}
}
if err = c.cacheAdd(result, list.Bytes, list.Name, rt); err != nil {
return nil, fmt.Errorf("failed to set network %q cached result: %w", list.Name, err)
}
return result, nil
} | AddNetworkList executes a sequence of plugins with the ADD command | AddNetworkList | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/api.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/api.go | Apache-2.0 |
func (c *CNIConfig) CheckNetworkList(ctx context.Context, list *NetworkConfigList, rt *RuntimeConf) error {
// CHECK was added in CNI spec version 0.4.0 and higher
if gtet, err := version.GreaterThanOrEqualTo(list.CNIVersion, "0.4.0"); err != nil {
return err
} else if !gtet {
return fmt.Errorf("configuration version %q %w", list.CNIVersion, ErrorCheckNotSupp)
}
if list.DisableCheck {
return nil
}
cachedResult, err := c.getCachedResult(list.Name, list.CNIVersion, rt)
if err != nil {
return fmt.Errorf("failed to get network %q cached result: %w", list.Name, err)
}
for _, net := range list.Plugins {
if err := c.checkNetwork(ctx, list.Name, list.CNIVersion, net, cachedResult, rt); err != nil {
return err
}
}
return nil
} | CheckNetworkList executes a sequence of plugins with the CHECK command | CheckNetworkList | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/api.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/api.go | Apache-2.0 |
func (c *CNIConfig) DelNetworkList(ctx context.Context, list *NetworkConfigList, rt *RuntimeConf) error {
var cachedResult types.Result
// Cached result on DEL was added in CNI spec version 0.4.0 and higher
if gtet, err := version.GreaterThanOrEqualTo(list.CNIVersion, "0.4.0"); err != nil {
return err
} else if gtet {
if cachedResult, err = c.getCachedResult(list.Name, list.CNIVersion, rt); err != nil {
_ = c.cacheDel(list.Name, rt)
cachedResult = nil
}
}
for i := len(list.Plugins) - 1; i >= 0; i-- {
net := list.Plugins[i]
if err := c.delNetwork(ctx, list.Name, list.CNIVersion, net, cachedResult, rt); err != nil {
return fmt.Errorf("plugin %s failed (delete): %w", pluginDescription(net.Network), err)
}
}
_ = c.cacheDel(list.Name, rt)
return nil
} | DelNetworkList executes a sequence of plugins with the DEL command | DelNetworkList | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/api.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/api.go | Apache-2.0 |
func (c *CNIConfig) AddNetwork(ctx context.Context, net *PluginConfig, rt *RuntimeConf) (types.Result, error) {
result, err := c.addNetwork(ctx, net.Network.Name, net.Network.CNIVersion, net, nil, rt)
if err != nil {
return nil, err
}
if err = c.cacheAdd(result, net.Bytes, net.Network.Name, rt); err != nil {
return nil, fmt.Errorf("failed to set network %q cached result: %w", net.Network.Name, err)
}
return result, nil
} | AddNetwork executes the plugin with the ADD command | AddNetwork | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/api.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/api.go | Apache-2.0 |
func (c *CNIConfig) CheckNetwork(ctx context.Context, net *PluginConfig, rt *RuntimeConf) error {
// CHECK was added in CNI spec version 0.4.0 and higher
if gtet, err := version.GreaterThanOrEqualTo(net.Network.CNIVersion, "0.4.0"); err != nil {
return err
} else if !gtet {
return fmt.Errorf("configuration version %q %w", net.Network.CNIVersion, ErrorCheckNotSupp)
}
cachedResult, err := c.getCachedResult(net.Network.Name, net.Network.CNIVersion, rt)
if err != nil {
return fmt.Errorf("failed to get network %q cached result: %w", net.Network.Name, err)
}
return c.checkNetwork(ctx, net.Network.Name, net.Network.CNIVersion, net, cachedResult, rt)
} | CheckNetwork executes the plugin with the CHECK command | CheckNetwork | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/api.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/api.go | Apache-2.0 |
func (c *CNIConfig) DelNetwork(ctx context.Context, net *PluginConfig, rt *RuntimeConf) error {
var cachedResult types.Result
// Cached result on DEL was added in CNI spec version 0.4.0 and higher
if gtet, err := version.GreaterThanOrEqualTo(net.Network.CNIVersion, "0.4.0"); err != nil {
return err
} else if gtet {
cachedResult, err = c.getCachedResult(net.Network.Name, net.Network.CNIVersion, rt)
if err != nil {
return fmt.Errorf("failed to get network %q cached result: %w", net.Network.Name, err)
}
}
if err := c.delNetwork(ctx, net.Network.Name, net.Network.CNIVersion, net, cachedResult, rt); err != nil {
return err
}
_ = c.cacheDel(net.Network.Name, rt)
return nil
} | DelNetwork executes the plugin with the DEL command | DelNetwork | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/api.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/api.go | Apache-2.0 |
func (c *CNIConfig) ValidateNetworkList(ctx context.Context, list *NetworkConfigList) ([]string, error) {
version := list.CNIVersion
// holding map for seen caps (in case of duplicates)
caps := map[string]interface{}{}
errs := []error{}
for _, net := range list.Plugins {
if err := c.validatePlugin(ctx, net.Network.Type, version); err != nil {
errs = append(errs, err)
}
for c, enabled := range net.Network.Capabilities {
if !enabled {
continue
}
caps[c] = struct{}{}
}
}
if len(errs) > 0 {
return nil, fmt.Errorf("%v", errs)
}
// make caps list
cc := make([]string, 0, len(caps))
for c := range caps {
cc = append(cc, c)
}
return cc, nil
} | ValidateNetworkList checks that a configuration is reasonably valid.
- all the specified plugins exist on disk
- every plugin supports the desired version.
Returns a list of all capabilities supported by the configuration, or error | ValidateNetworkList | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/api.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/api.go | Apache-2.0 |
func (c *CNIConfig) ValidateNetwork(ctx context.Context, net *PluginConfig) ([]string, error) {
caps := []string{}
for c, ok := range net.Network.Capabilities {
if ok {
caps = append(caps, c)
}
}
if err := c.validatePlugin(ctx, net.Network.Type, net.Network.CNIVersion); err != nil {
return nil, err
}
return caps, nil
} | ValidateNetwork checks that a configuration is reasonably valid.
It uses the same logic as ValidateNetworkList)
Returns a list of capabilities | ValidateNetwork | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/api.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/api.go | Apache-2.0 |
func (c *CNIConfig) validatePlugin(ctx context.Context, pluginName, expectedVersion string) error {
c.ensureExec()
pluginPath, err := c.exec.FindInPath(pluginName, c.Path)
if err != nil {
return err
}
if expectedVersion == "" {
expectedVersion = "0.1.0"
}
vi, err := invoke.GetVersionInfo(ctx, pluginPath, c.exec)
if err != nil {
return err
}
for _, vers := range vi.SupportedVersions() {
if vers == expectedVersion {
return nil
}
}
return fmt.Errorf("plugin %s does not support config version %q", pluginName, expectedVersion)
} | validatePlugin checks that an individual plugin's configuration is sane | validatePlugin | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/api.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/api.go | Apache-2.0 |
func (c *CNIConfig) GetVersionInfo(ctx context.Context, pluginType string) (version.PluginInfo, error) {
c.ensureExec()
pluginPath, err := c.exec.FindInPath(pluginType, c.Path)
if err != nil {
return nil, err
}
return invoke.GetVersionInfo(ctx, pluginPath, c.exec)
} | GetVersionInfo reports which versions of the CNI spec are supported by
the given plugin. | GetVersionInfo | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/api.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/api.go | Apache-2.0 |
func (c *CNIConfig) GCNetworkList(ctx context.Context, list *NetworkConfigList, args *GCArgs) error {
// If DisableGC is set, then don't bother GCing at all.
if list.DisableGC {
return nil
}
// First, get the list of cached attachments
cachedAttachments, err := c.GetCachedAttachments("")
if err != nil {
return nil
}
var validAttachments map[types.GCAttachment]interface{}
if args != nil {
validAttachments = make(map[types.GCAttachment]interface{}, len(args.ValidAttachments))
for _, a := range args.ValidAttachments {
validAttachments[a] = nil
}
}
var errs []error
for _, cachedAttachment := range cachedAttachments {
if cachedAttachment.Network != list.Name {
continue
}
// we found this attachment
gca := types.GCAttachment{
ContainerID: cachedAttachment.ContainerID,
IfName: cachedAttachment.IfName,
}
if _, ok := validAttachments[gca]; ok {
continue
}
// otherwise, this attachment wasn't valid and we should issue a CNI DEL
rt := RuntimeConf{
ContainerID: cachedAttachment.ContainerID,
NetNS: cachedAttachment.NetNS,
IfName: cachedAttachment.IfName,
Args: cachedAttachment.CniArgs,
CapabilityArgs: cachedAttachment.CapabilityArgs,
}
if err := c.DelNetworkList(ctx, list, &rt); err != nil {
errs = append(errs, fmt.Errorf("failed to delete stale attachment %s %s: %w", rt.ContainerID, rt.IfName, err))
}
}
// now, if the version supports it, issue a GC
if gt, _ := version.GreaterThanOrEqualTo(list.CNIVersion, "1.1.0"); gt {
inject := map[string]interface{}{
"name": list.Name,
"cniVersion": list.CNIVersion,
}
if args != nil {
inject["cni.dev/valid-attachments"] = args.ValidAttachments
// #1101: spec used incorrect variable name
inject["cni.dev/attachments"] = args.ValidAttachments
}
for _, plugin := range list.Plugins {
// build config here
pluginConfig, err := InjectConf(plugin, inject)
if err != nil {
errs = append(errs, fmt.Errorf("failed to generate configuration to GC plugin %s: %w", plugin.Network.Type, err))
}
if err := c.gcNetwork(ctx, pluginConfig); err != nil {
errs = append(errs, fmt.Errorf("failed to GC plugin %s: %w", plugin.Network.Type, err))
}
}
}
return errors.Join(errs...)
} | GCNetworkList will do two things
- dump the list of cached attachments, and issue deletes as necessary
- issue a GC to the underlying plugins (if the version is high enough) | GCNetworkList | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/containernetworking/cni/libcni/api.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/containernetworking/cni/libcni/api.go | Apache-2.0 |
func (o Operation) Kind() string {
if obj, ok := o["op"]; ok && obj != nil {
var op string
err := json.Unmarshal(*obj, &op)
if err != nil {
return "unknown"
}
return op
}
return "unknown"
} | Kind reads the "op" field of the Operation. | Kind | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/evanphx/json-patch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/evanphx/json-patch/patch.go | Apache-2.0 |
func (o Operation) Path() (string, error) {
if obj, ok := o["path"]; ok && obj != nil {
var op string
err := json.Unmarshal(*obj, &op)
if err != nil {
return "unknown", err
}
return op, nil
}
return "unknown", errors.Wrapf(ErrMissing, "operation missing path field")
} | Path reads the "path" field of the Operation. | Path | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/evanphx/json-patch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/evanphx/json-patch/patch.go | Apache-2.0 |
func (o Operation) From() (string, error) {
if obj, ok := o["from"]; ok && obj != nil {
var op string
err := json.Unmarshal(*obj, &op)
if err != nil {
return "unknown", err
}
return op, nil
}
return "unknown", errors.Wrapf(ErrMissing, "operation, missing from field")
} | From reads the "from" field of the Operation. | From | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/evanphx/json-patch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/evanphx/json-patch/patch.go | Apache-2.0 |
func (o Operation) ValueInterface() (interface{}, error) {
if obj, ok := o["value"]; ok && obj != nil {
var v interface{}
err := json.Unmarshal(*obj, &v)
if err != nil {
return nil, err
}
return v, nil
}
return nil, errors.Wrapf(ErrMissing, "operation, missing value field")
} | ValueInterface decodes the operation value into an interface. | ValueInterface | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/evanphx/json-patch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/evanphx/json-patch/patch.go | Apache-2.0 |
func (d *partialArray) set(key string, val *lazyNode) error {
idx, err := strconv.Atoi(key)
if err != nil {
return err
}
if idx < 0 {
if !SupportNegativeIndices {
return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx)
}
if idx < -len(*d) {
return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx)
}
idx += len(*d)
}
(*d)[idx] = val
return nil
} | set should only be used to implement the "replace" operation, so "key" must
be an already existing index in "d". | set | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/evanphx/json-patch/patch.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/evanphx/json-patch/patch.go | Apache-2.0 |
func NewAccumulatedCopySizeError(l, a int64) *AccumulatedCopySizeError {
return &AccumulatedCopySizeError{limit: l, accumulated: a}
} | NewAccumulatedCopySizeError returns an AccumulatedCopySizeError. | NewAccumulatedCopySizeError | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/evanphx/json-patch/errors.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/evanphx/json-patch/errors.go | Apache-2.0 |
func (a *AccumulatedCopySizeError) Error() string {
return fmt.Sprintf("Unable to complete the copy, the accumulated size increase of copy is %d, exceeding the limit %d", a.accumulated, a.limit)
} | Error implements the error interface. | Error | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/evanphx/json-patch/errors.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/evanphx/json-patch/errors.go | Apache-2.0 |
func NewArraySizeError(l, s int) *ArraySizeError {
return &ArraySizeError{limit: l, size: s}
} | NewArraySizeError returns an ArraySizeError. | NewArraySizeError | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/evanphx/json-patch/errors.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/evanphx/json-patch/errors.go | Apache-2.0 |
func (a *ArraySizeError) Error() string {
return fmt.Sprintf("Unable to create array of size %d, limit is %d", a.size, a.limit)
} | Error implements the error interface. | Error | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/evanphx/json-patch/errors.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/evanphx/json-patch/errors.go | Apache-2.0 |
func MergeMergePatches(patch1Data, patch2Data []byte) ([]byte, error) {
return doMergePatch(patch1Data, patch2Data, true)
} | MergeMergePatches merges two merge patches together, such that
applying this resulting merged merge patch to a document yields the same
as merging each merge patch to the document in succession. | MergeMergePatches | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/evanphx/json-patch/merge.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/evanphx/json-patch/merge.go | Apache-2.0 |
func MergePatch(docData, patchData []byte) ([]byte, error) {
return doMergePatch(docData, patchData, false)
} | MergePatch merges the patchData into the docData. | MergePatch | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/evanphx/json-patch/merge.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/evanphx/json-patch/merge.go | Apache-2.0 |
func resemblesJSONArray(input []byte) bool {
input = bytes.TrimSpace(input)
hasPrefix := bytes.HasPrefix(input, []byte("["))
hasSuffix := bytes.HasSuffix(input, []byte("]"))
return hasPrefix && hasSuffix
} | resemblesJSONArray indicates whether the byte-slice "appears" to be
a JSON array or not.
False-positives are possible, as this function does not check the internal
structure of the array. It only checks that the outer syntax is present and
correct. | resemblesJSONArray | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/evanphx/json-patch/merge.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/evanphx/json-patch/merge.go | Apache-2.0 |
func CreateMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) {
originalResemblesArray := resemblesJSONArray(originalJSON)
modifiedResemblesArray := resemblesJSONArray(modifiedJSON)
// Do both byte-slices seem like JSON arrays?
if originalResemblesArray && modifiedResemblesArray {
return createArrayMergePatch(originalJSON, modifiedJSON)
}
// Are both byte-slices are not arrays? Then they are likely JSON objects...
if !originalResemblesArray && !modifiedResemblesArray {
return createObjectMergePatch(originalJSON, modifiedJSON)
}
// None of the above? Then return an error because of mismatched types.
return nil, errBadMergeTypes
} | CreateMergePatch will return a merge patch document capable of converting
the original document(s) to the modified document(s).
The parameters can be bytes of either two JSON Documents, or two arrays of
JSON documents.
The merge patch returned follows the specification defined at http://tools.ietf.org/html/draft-ietf-appsawg-json-merge-patch-07 | CreateMergePatch | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/evanphx/json-patch/merge.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/evanphx/json-patch/merge.go | Apache-2.0 |
func createObjectMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) {
originalDoc := map[string]interface{}{}
modifiedDoc := map[string]interface{}{}
err := json.Unmarshal(originalJSON, &originalDoc)
if err != nil {
return nil, ErrBadJSONDoc
}
err = json.Unmarshal(modifiedJSON, &modifiedDoc)
if err != nil {
return nil, ErrBadJSONDoc
}
dest, err := getDiff(originalDoc, modifiedDoc)
if err != nil {
return nil, err
}
return json.Marshal(dest)
} | createObjectMergePatch will return a merge-patch document capable of
converting the original document to the modified document. | createObjectMergePatch | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/evanphx/json-patch/merge.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/evanphx/json-patch/merge.go | Apache-2.0 |
func createArrayMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) {
originalDocs := []json.RawMessage{}
modifiedDocs := []json.RawMessage{}
err := json.Unmarshal(originalJSON, &originalDocs)
if err != nil {
return nil, ErrBadJSONDoc
}
err = json.Unmarshal(modifiedJSON, &modifiedDocs)
if err != nil {
return nil, ErrBadJSONDoc
}
total := len(originalDocs)
if len(modifiedDocs) != total {
return nil, ErrBadJSONDoc
}
result := []json.RawMessage{}
for i := 0; i < len(originalDocs); i++ {
original := originalDocs[i]
modified := modifiedDocs[i]
patch, err := createObjectMergePatch(original, modified)
if err != nil {
return nil, err
}
result = append(result, json.RawMessage(patch))
}
return json.Marshal(result)
} | createArrayMergePatch will return an array of merge-patch documents capable
of converting the original document to the modified document for each
pair of JSON documents provided in the arrays.
Arrays of mismatched sizes will result in an error. | createArrayMergePatch | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/evanphx/json-patch/merge.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/evanphx/json-patch/merge.go | Apache-2.0 |
func matchesArray(a, b []interface{}) bool {
if len(a) != len(b) {
return false
}
if (a == nil && b != nil) || (a != nil && b == nil) {
return false
}
for i := range a {
if !matchesValue(a[i], b[i]) {
return false
}
}
return true
} | Returns true if the array matches (must be json types).
As is idiomatic for go, an empty array is not the same as a nil array. | matchesArray | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/evanphx/json-patch/merge.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/evanphx/json-patch/merge.go | Apache-2.0 |
func matchesValue(av, bv interface{}) bool {
if reflect.TypeOf(av) != reflect.TypeOf(bv) {
return false
}
switch at := av.(type) {
case string:
bt := bv.(string)
if bt == at {
return true
}
case float64:
bt := bv.(float64)
if bt == at {
return true
}
case bool:
bt := bv.(bool)
if bt == at {
return true
}
case nil:
// Both nil, fine.
return true
case map[string]interface{}:
bt := bv.(map[string]interface{})
if len(bt) != len(at) {
return false
}
for key := range bt {
av, aOK := at[key]
bv, bOK := bt[key]
if aOK != bOK {
return false
}
if !matchesValue(av, bv) {
return false
}
}
return true
case []interface{}:
bt := bv.([]interface{})
return matchesArray(at, bt)
} | Returns true if the values matches (must be json types)
The types of the values must match, otherwise it will always return false
If two map[string]interface{} are given, all elements must match. | matchesValue | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/evanphx/json-patch/merge.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/evanphx/json-patch/merge.go | Apache-2.0 |
func getDiff(a, b map[string]interface{}) (map[string]interface{}, error) {
into := map[string]interface{}{}
for key, bv := range b {
av, ok := a[key]
// value was added
if !ok {
into[key] = bv
continue
}
// If types have changed, replace completely
if reflect.TypeOf(av) != reflect.TypeOf(bv) {
into[key] = bv
continue
}
// Types are the same, compare values
switch at := av.(type) {
case map[string]interface{}:
bt := bv.(map[string]interface{})
dst := make(map[string]interface{}, len(bt))
dst, err := getDiff(at, bt)
if err != nil {
return nil, err
}
if len(dst) > 0 {
into[key] = dst
}
case string, float64, bool:
if !matchesValue(av, bv) {
into[key] = bv
}
case []interface{}:
bt := bv.([]interface{})
if !matchesArray(at, bt) {
into[key] = bv
}
case nil:
switch bv.(type) {
case nil:
// Both nil, fine.
default:
into[key] = bv
}
default:
panic(fmt.Sprintf("Unknown type:%T in key %s", av, key))
} | getDiff returns the (recursive) difference between a and b as a map[string]interface{}. | getDiff | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/evanphx/json-patch/merge.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/evanphx/json-patch/merge.go | Apache-2.0 |
func extractFile(gz []byte) (*FileDescriptorProto, error) {
r, err := gzip.NewReader(bytes.NewReader(gz))
if err != nil {
return nil, fmt.Errorf("failed to open gzip reader: %v", err)
}
defer r.Close()
b, err := ioutil.ReadAll(r)
if err != nil {
return nil, fmt.Errorf("failed to uncompress descriptor: %v", err)
}
fd := new(FileDescriptorProto)
if err := proto.Unmarshal(b, fd); err != nil {
return nil, fmt.Errorf("malformed FileDescriptorProto: %v", err)
}
return fd, nil
} | extractFile extracts a FileDescriptorProto from a gzip'd buffer. | extractFile | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.go | Apache-2.0 |
func ForMessage(msg Message) (fd *FileDescriptorProto, md *DescriptorProto) {
gz, path := msg.Descriptor()
fd, err := extractFile(gz)
if err != nil {
panic(fmt.Sprintf("invalid FileDescriptorProto for %T: %v", msg, err))
}
md = fd.MessageType[path[0]]
for _, i := range path[1:] {
md = md.NestedType[i]
}
return fd, md
} | ForMessage returns a FileDescriptorProto and a DescriptorProto from within it
describing the given message. | ForMessage | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.go | Apache-2.0 |
func (field *FieldDescriptorProto) IsScalar() bool {
if field.Type == nil {
return false
}
switch *field.Type {
case FieldDescriptorProto_TYPE_DOUBLE,
FieldDescriptorProto_TYPE_FLOAT,
FieldDescriptorProto_TYPE_INT64,
FieldDescriptorProto_TYPE_UINT64,
FieldDescriptorProto_TYPE_INT32,
FieldDescriptorProto_TYPE_FIXED64,
FieldDescriptorProto_TYPE_FIXED32,
FieldDescriptorProto_TYPE_BOOL,
FieldDescriptorProto_TYPE_UINT32,
FieldDescriptorProto_TYPE_ENUM,
FieldDescriptorProto_TYPE_SFIXED32,
FieldDescriptorProto_TYPE_SFIXED64,
FieldDescriptorProto_TYPE_SINT32,
FieldDescriptorProto_TYPE_SINT64:
return true
default:
return false
}
} | Is this field a scalar numeric type? | IsScalar | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.go | Apache-2.0 |
func (m *FileOptions) GetJavaGenerateEqualsAndHash() bool {
if m != nil && m.JavaGenerateEqualsAndHash != nil {
return *m.JavaGenerateEqualsAndHash
}
return false
} | Deprecated: Do not use. | GetJavaGenerateEqualsAndHash | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.pb.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/protoc-gen-gogo/descriptor/descriptor.pb.go | Apache-2.0 |
func validateTimestamp(ts *timestamp) error {
if ts == nil {
return errors.New("timestamp: nil Timestamp")
}
if ts.Seconds < minValidSeconds {
return fmt.Errorf("timestamp: %#v before 0001-01-01", ts)
}
if ts.Seconds >= maxValidSeconds {
return fmt.Errorf("timestamp: %#v after 10000-01-01", ts)
}
if ts.Nanos < 0 || ts.Nanos >= 1e9 {
return fmt.Errorf("timestamp: %#v: nanos not in range [0, 1e9)", ts)
}
return nil
} | validateTimestamp determines whether a Timestamp is valid.
A valid timestamp represents a time in the range
[0001-01-01, 10000-01-01) and has a Nanos field
in the range [0, 1e9).
If the Timestamp is valid, validateTimestamp returns nil.
Otherwise, it returns an error that describes
the problem.
Every valid Timestamp can be represented by a time.Time, but the converse is not true. | validateTimestamp | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/timestamp.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/timestamp.go | Apache-2.0 |
func timestampFromProto(ts *timestamp) (time.Time, error) {
// Don't return the zero value on error, because corresponds to a valid
// timestamp. Instead return whatever time.Unix gives us.
var t time.Time
if ts == nil {
t = time.Unix(0, 0).UTC() // treat nil like the empty Timestamp
} else {
t = time.Unix(ts.Seconds, int64(ts.Nanos)).UTC()
}
return t, validateTimestamp(ts)
} | TimestampFromProto converts a google.protobuf.Timestamp proto to a time.Time.
It returns an error if the argument is invalid.
Unlike most Go functions, if Timestamp returns an error, the first return value
is not the zero time.Time. Instead, it is the value obtained from the
time.Unix function when passed the contents of the Timestamp, in the UTC
locale. This may or may not be a meaningful time; many invalid Timestamps
do map to valid time.Times.
A nil Timestamp returns an error. The first return value in that case is
undefined. | timestampFromProto | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/timestamp.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/timestamp.go | Apache-2.0 |
func timestampProto(t time.Time) (*timestamp, error) {
seconds := t.Unix()
nanos := int32(t.Sub(time.Unix(seconds, 0)))
ts := ×tamp{
Seconds: seconds,
Nanos: nanos,
}
if err := validateTimestamp(ts); err != nil {
return nil, err
}
return ts, nil
} | TimestampProto converts the time.Time to a google.protobuf.Timestamp proto.
It returns an error if the resulting Timestamp is invalid. | timestampProto | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/timestamp.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/timestamp.go | Apache-2.0 |
func makeMessageRefMarshaler(u *marshalInfo) (sizer, marshaler) {
return func(ptr pointer, tagsize int) int {
siz := u.size(ptr)
return siz + SizeVarint(uint64(siz)) + tagsize
},
func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
b = appendVarint(b, wiretag)
siz := u.cachedsize(ptr)
b = appendVarint(b, uint64(siz))
return u.marshal(b, ptr, deterministic)
}
} | makeMessageRefMarshaler differs a bit from makeMessageMarshaler
It marshal a message T instead of a *T | makeMessageRefMarshaler | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/table_marshal_gogo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/table_marshal_gogo.go | Apache-2.0 |
func makeMessageRefSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
return func(ptr pointer, tagsize int) int {
s := ptr.getSlice(u.typ)
n := 0
for i := 0; i < s.Len(); i++ {
elem := s.Index(i)
e := elem.Interface()
v := toAddrPointer(&e, false)
siz := u.size(v)
n += siz + SizeVarint(uint64(siz)) + tagsize
}
return n
},
func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
s := ptr.getSlice(u.typ)
var err, errreq error
for i := 0; i < s.Len(); i++ {
elem := s.Index(i)
e := elem.Interface()
v := toAddrPointer(&e, false)
b = appendVarint(b, wiretag)
siz := u.size(v)
b = appendVarint(b, uint64(siz))
b, err = u.marshal(b, v, deterministic)
if err != nil {
if _, ok := err.(*RequiredNotSetError); ok {
// Required field in submessage is not set.
// We record the error but keep going, to give a complete marshaling.
if errreq == nil {
errreq = err
}
continue
}
if err == ErrNil {
err = errRepeatedHasNil
}
return b, err
}
}
return b, errreq
}
} | makeMessageRefSliceMarshaler differs quite a lot from makeMessageSliceMarshaler
It marshals a slice of messages []T instead of []*T | makeMessageRefSliceMarshaler | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/table_marshal_gogo.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/table_marshal_gogo.go | Apache-2.0 |
func (a *InternalMessageInfo) Unmarshal(msg Message, b []byte) error {
// Load the unmarshal information for this message type.
// The atomic load ensures memory consistency.
u := atomicLoadUnmarshalInfo(&a.unmarshal)
if u == nil {
// Slow path: find unmarshal info for msg, update a with it.
u = getUnmarshalInfo(reflect.TypeOf(msg).Elem())
atomicStoreUnmarshalInfo(&a.unmarshal, u)
}
// Then do the unmarshaling.
err := u.unmarshal(toPointer(&msg), b)
return err
} | Unmarshal is the entry point from the generated .pb.go files.
This function is not intended to be used by non-generated code.
This function is not subject to any compatibility guarantee.
msg contains a pointer to a protocol buffer struct.
b is the data to be unmarshaled into the protocol buffer.
a is a pointer to a place to store cached unmarshal information. | Unmarshal | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/table_unmarshal.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/table_unmarshal.go | Apache-2.0 |
func getUnmarshalInfo(t reflect.Type) *unmarshalInfo {
// It would be correct to return a new unmarshalInfo
// unconditionally. We would end up allocating one
// per occurrence of that type as a message or submessage.
// We use a cache here just to reduce memory usage.
unmarshalInfoLock.Lock()
defer unmarshalInfoLock.Unlock()
u := unmarshalInfoMap[t]
if u == nil {
u = &unmarshalInfo{typ: t}
// Note: we just set the type here. The rest of the fields
// will be initialized on first use.
unmarshalInfoMap[t] = u
}
return u
} | getUnmarshalInfo returns the data structure which can be
subsequently used to unmarshal a message of the given type.
t is the type of the message (note: not pointer to message). | getUnmarshalInfo | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/table_unmarshal.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/table_unmarshal.go | Apache-2.0 |
func (u *unmarshalInfo) unmarshal(m pointer, b []byte) error {
if atomic.LoadInt32(&u.initialized) == 0 {
u.computeUnmarshalInfo()
}
if u.isMessageSet {
return unmarshalMessageSet(b, m.offset(u.extensions).toExtensions())
}
var reqMask uint64 // bitmask of required fields we've seen.
var errLater error
for len(b) > 0 {
// Read tag and wire type.
// Special case 1 and 2 byte varints.
var x uint64
if b[0] < 128 {
x = uint64(b[0])
b = b[1:]
} else if len(b) >= 2 && b[1] < 128 {
x = uint64(b[0]&0x7f) + uint64(b[1])<<7
b = b[2:]
} else {
var n int
x, n = decodeVarint(b)
if n == 0 {
return io.ErrUnexpectedEOF
}
b = b[n:]
}
tag := x >> 3
wire := int(x) & 7
// Dispatch on the tag to one of the unmarshal* functions below.
var f unmarshalFieldInfo
if tag < uint64(len(u.dense)) {
f = u.dense[tag]
} else {
f = u.sparse[tag]
}
if fn := f.unmarshal; fn != nil {
var err error
b, err = fn(b, m.offset(f.field), wire)
if err == nil {
reqMask |= f.reqMask
continue
}
if r, ok := err.(*RequiredNotSetError); ok {
// Remember this error, but keep parsing. We need to produce
// a full parse even if a required field is missing.
if errLater == nil {
errLater = r
}
reqMask |= f.reqMask
continue
}
if err != errInternalBadWireType {
if err == errInvalidUTF8 {
if errLater == nil {
fullName := revProtoTypes[reflect.PtrTo(u.typ)] + "." + f.name
errLater = &invalidUTF8Error{fullName}
}
continue
}
return err
}
// Fragments with bad wire type are treated as unknown fields.
}
// Unknown tag.
if !u.unrecognized.IsValid() {
// Don't keep unrecognized data; just skip it.
var err error
b, err = skipField(b, wire)
if err != nil {
return err
}
continue
}
// Keep unrecognized data around.
// maybe in extensions, maybe in the unrecognized field.
z := m.offset(u.unrecognized).toBytes()
var emap map[int32]Extension
var e Extension
for _, r := range u.extensionRanges {
if uint64(r.Start) <= tag && tag <= uint64(r.End) {
if u.extensions.IsValid() {
mp := m.offset(u.extensions).toExtensions()
emap = mp.extensionsWrite()
e = emap[int32(tag)]
z = &e.enc
break
}
if u.oldExtensions.IsValid() {
p := m.offset(u.oldExtensions).toOldExtensions()
emap = *p
if emap == nil {
emap = map[int32]Extension{}
*p = emap
}
e = emap[int32(tag)]
z = &e.enc
break
}
if u.bytesExtensions.IsValid() {
z = m.offset(u.bytesExtensions).toBytes()
break
}
panic("no extensions field available")
}
}
// Use wire type to skip data.
var err error
b0 := b
b, err = skipField(b, wire)
if err != nil {
return err
}
*z = encodeVarint(*z, tag<<3|uint64(wire))
*z = append(*z, b0[:len(b0)-len(b)]...)
if emap != nil {
emap[int32(tag)] = e
}
}
if reqMask != u.reqMask && errLater == nil {
// A required field of this message is missing.
for _, n := range u.reqFields {
if reqMask&1 == 0 {
errLater = &RequiredNotSetError{n}
}
reqMask >>= 1
}
}
return errLater
} | unmarshal does the main work of unmarshaling a message.
u provides type information used to unmarshal the message.
m is a pointer to a protocol buffer message.
b is a byte stream to unmarshal into m.
This is top routine used when recursively unmarshaling submessages. | unmarshal | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/table_unmarshal.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/table_unmarshal.go | Apache-2.0 |
func (u *unmarshalInfo) computeUnmarshalInfo() {
u.lock.Lock()
defer u.lock.Unlock()
if u.initialized != 0 {
return
}
t := u.typ
n := t.NumField()
// Set up the "not found" value for the unrecognized byte buffer.
// This is the default for proto3.
u.unrecognized = invalidField
u.extensions = invalidField
u.oldExtensions = invalidField
u.bytesExtensions = invalidField
// List of the generated type and offset for each oneof field.
type oneofField struct {
ityp reflect.Type // interface type of oneof field
field field // offset in containing message
}
var oneofFields []oneofField
for i := 0; i < n; i++ {
f := t.Field(i)
if f.Name == "XXX_unrecognized" {
// The byte slice used to hold unrecognized input is special.
if f.Type != reflect.TypeOf(([]byte)(nil)) {
panic("bad type for XXX_unrecognized field: " + f.Type.Name())
}
u.unrecognized = toField(&f)
continue
}
if f.Name == "XXX_InternalExtensions" {
// Ditto here.
if f.Type != reflect.TypeOf(XXX_InternalExtensions{}) {
panic("bad type for XXX_InternalExtensions field: " + f.Type.Name())
}
u.extensions = toField(&f)
if f.Tag.Get("protobuf_messageset") == "1" {
u.isMessageSet = true
}
continue
}
if f.Name == "XXX_extensions" {
// An older form of the extensions field.
if f.Type == reflect.TypeOf((map[int32]Extension)(nil)) {
u.oldExtensions = toField(&f)
continue
} else if f.Type == reflect.TypeOf(([]byte)(nil)) {
u.bytesExtensions = toField(&f)
continue
}
panic("bad type for XXX_extensions field: " + f.Type.Name())
}
if f.Name == "XXX_NoUnkeyedLiteral" || f.Name == "XXX_sizecache" {
continue
}
oneof := f.Tag.Get("protobuf_oneof")
if oneof != "" {
oneofFields = append(oneofFields, oneofField{f.Type, toField(&f)})
// The rest of oneof processing happens below.
continue
}
tags := f.Tag.Get("protobuf")
tagArray := strings.Split(tags, ",")
if len(tagArray) < 2 {
panic("protobuf tag not enough fields in " + t.Name() + "." + f.Name + ": " + tags)
}
tag, err := strconv.Atoi(tagArray[1])
if err != nil {
panic("protobuf tag field not an integer: " + tagArray[1])
}
name := ""
for _, tag := range tagArray[3:] {
if strings.HasPrefix(tag, "name=") {
name = tag[5:]
}
}
// Extract unmarshaling function from the field (its type and tags).
unmarshal := fieldUnmarshaler(&f)
// Required field?
var reqMask uint64
if tagArray[2] == "req" {
bit := len(u.reqFields)
u.reqFields = append(u.reqFields, name)
reqMask = uint64(1) << uint(bit)
// TODO: if we have more than 64 required fields, we end up
// not verifying that all required fields are present.
// Fix this, perhaps using a count of required fields?
}
// Store the info in the correct slot in the message.
u.setTag(tag, toField(&f), unmarshal, reqMask, name)
}
// Find any types associated with oneof fields.
// gogo: len(oneofFields) > 0 is needed for embedded oneof messages, without a marshaler and unmarshaler
if len(oneofFields) > 0 {
var oneofImplementers []interface{}
switch m := reflect.Zero(reflect.PtrTo(t)).Interface().(type) {
case oneofFuncsIface:
_, _, _, oneofImplementers = m.XXX_OneofFuncs()
case oneofWrappersIface:
oneofImplementers = m.XXX_OneofWrappers()
}
for _, v := range oneofImplementers {
tptr := reflect.TypeOf(v) // *Msg_X
typ := tptr.Elem() // Msg_X
f := typ.Field(0) // oneof implementers have one field
baseUnmarshal := fieldUnmarshaler(&f)
tags := strings.Split(f.Tag.Get("protobuf"), ",")
fieldNum, err := strconv.Atoi(tags[1])
if err != nil {
panic("protobuf tag field not an integer: " + tags[1])
}
var name string
for _, tag := range tags {
if strings.HasPrefix(tag, "name=") {
name = strings.TrimPrefix(tag, "name=")
break
}
}
// Find the oneof field that this struct implements.
// Might take O(n^2) to process all of the oneofs, but who cares.
for _, of := range oneofFields {
if tptr.Implements(of.ityp) {
// We have found the corresponding interface for this struct.
// That lets us know where this struct should be stored
// when we encounter it during unmarshaling.
unmarshal := makeUnmarshalOneof(typ, of.ityp, baseUnmarshal)
u.setTag(fieldNum, of.field, unmarshal, 0, name)
}
}
}
} | computeUnmarshalInfo fills in u with information for use
in unmarshaling protocol buffers of type u.typ. | computeUnmarshalInfo | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/table_unmarshal.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/table_unmarshal.go | Apache-2.0 |
func fieldUnmarshaler(f *reflect.StructField) unmarshaler {
if f.Type.Kind() == reflect.Map {
return makeUnmarshalMap(f)
}
return typeUnmarshaler(f.Type, f.Tag.Get("protobuf"))
} | fieldUnmarshaler returns an unmarshaler for the given field. | fieldUnmarshaler | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/table_unmarshal.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/table_unmarshal.go | Apache-2.0 |
func typeUnmarshaler(t reflect.Type, tags string) unmarshaler {
tagArray := strings.Split(tags, ",")
encoding := tagArray[0]
name := "unknown"
ctype := false
isTime := false
isDuration := false
isWktPointer := false
proto3 := false
validateUTF8 := true
for _, tag := range tagArray[3:] {
if strings.HasPrefix(tag, "name=") {
name = tag[5:]
}
if tag == "proto3" {
proto3 = true
}
if strings.HasPrefix(tag, "customtype=") {
ctype = true
}
if tag == "stdtime" {
isTime = true
}
if tag == "stdduration" {
isDuration = true
}
if tag == "wktptr" {
isWktPointer = true
}
}
validateUTF8 = validateUTF8 && proto3
// Figure out packaging (pointer, slice, or both)
slice := false
pointer := false
if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 {
slice = true
t = t.Elem()
}
if t.Kind() == reflect.Ptr {
pointer = true
t = t.Elem()
}
if ctype {
if reflect.PtrTo(t).Implements(customType) {
if slice {
return makeUnmarshalCustomSlice(getUnmarshalInfo(t), name)
}
if pointer {
return makeUnmarshalCustomPtr(getUnmarshalInfo(t), name)
}
return makeUnmarshalCustom(getUnmarshalInfo(t), name)
} else {
panic(fmt.Sprintf("custom type: type: %v, does not implement the proto.custom interface", t))
}
}
if isTime {
if pointer {
if slice {
return makeUnmarshalTimePtrSlice(getUnmarshalInfo(t), name)
}
return makeUnmarshalTimePtr(getUnmarshalInfo(t), name)
}
if slice {
return makeUnmarshalTimeSlice(getUnmarshalInfo(t), name)
}
return makeUnmarshalTime(getUnmarshalInfo(t), name)
}
if isDuration {
if pointer {
if slice {
return makeUnmarshalDurationPtrSlice(getUnmarshalInfo(t), name)
}
return makeUnmarshalDurationPtr(getUnmarshalInfo(t), name)
}
if slice {
return makeUnmarshalDurationSlice(getUnmarshalInfo(t), name)
}
return makeUnmarshalDuration(getUnmarshalInfo(t), name)
}
if isWktPointer {
switch t.Kind() {
case reflect.Float64:
if pointer {
if slice {
return makeStdDoubleValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name)
}
return makeStdDoubleValuePtrUnmarshaler(getUnmarshalInfo(t), name)
}
if slice {
return makeStdDoubleValueSliceUnmarshaler(getUnmarshalInfo(t), name)
}
return makeStdDoubleValueUnmarshaler(getUnmarshalInfo(t), name)
case reflect.Float32:
if pointer {
if slice {
return makeStdFloatValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name)
}
return makeStdFloatValuePtrUnmarshaler(getUnmarshalInfo(t), name)
}
if slice {
return makeStdFloatValueSliceUnmarshaler(getUnmarshalInfo(t), name)
}
return makeStdFloatValueUnmarshaler(getUnmarshalInfo(t), name)
case reflect.Int64:
if pointer {
if slice {
return makeStdInt64ValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name)
}
return makeStdInt64ValuePtrUnmarshaler(getUnmarshalInfo(t), name)
}
if slice {
return makeStdInt64ValueSliceUnmarshaler(getUnmarshalInfo(t), name)
}
return makeStdInt64ValueUnmarshaler(getUnmarshalInfo(t), name)
case reflect.Uint64:
if pointer {
if slice {
return makeStdUInt64ValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name)
}
return makeStdUInt64ValuePtrUnmarshaler(getUnmarshalInfo(t), name)
}
if slice {
return makeStdUInt64ValueSliceUnmarshaler(getUnmarshalInfo(t), name)
}
return makeStdUInt64ValueUnmarshaler(getUnmarshalInfo(t), name)
case reflect.Int32:
if pointer {
if slice {
return makeStdInt32ValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name)
}
return makeStdInt32ValuePtrUnmarshaler(getUnmarshalInfo(t), name)
}
if slice {
return makeStdInt32ValueSliceUnmarshaler(getUnmarshalInfo(t), name)
}
return makeStdInt32ValueUnmarshaler(getUnmarshalInfo(t), name)
case reflect.Uint32:
if pointer {
if slice {
return makeStdUInt32ValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name)
}
return makeStdUInt32ValuePtrUnmarshaler(getUnmarshalInfo(t), name)
}
if slice {
return makeStdUInt32ValueSliceUnmarshaler(getUnmarshalInfo(t), name)
}
return makeStdUInt32ValueUnmarshaler(getUnmarshalInfo(t), name)
case reflect.Bool:
if pointer {
if slice {
return makeStdBoolValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name)
}
return makeStdBoolValuePtrUnmarshaler(getUnmarshalInfo(t), name)
}
if slice {
return makeStdBoolValueSliceUnmarshaler(getUnmarshalInfo(t), name)
}
return makeStdBoolValueUnmarshaler(getUnmarshalInfo(t), name)
case reflect.String:
if pointer {
if slice {
return makeStdStringValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name)
}
return makeStdStringValuePtrUnmarshaler(getUnmarshalInfo(t), name)
}
if slice {
return makeStdStringValueSliceUnmarshaler(getUnmarshalInfo(t), name)
}
return makeStdStringValueUnmarshaler(getUnmarshalInfo(t), name)
case uint8SliceType:
if pointer {
if slice {
return makeStdBytesValuePtrSliceUnmarshaler(getUnmarshalInfo(t), name)
}
return makeStdBytesValuePtrUnmarshaler(getUnmarshalInfo(t), name)
}
if slice {
return makeStdBytesValueSliceUnmarshaler(getUnmarshalInfo(t), name)
}
return makeStdBytesValueUnmarshaler(getUnmarshalInfo(t), name)
default:
panic(fmt.Sprintf("unknown wktpointer type %#v", t))
}
}
// We'll never have both pointer and slice for basic types.
if pointer && slice && t.Kind() != reflect.Struct {
panic("both pointer and slice for basic type in " + t.Name())
}
switch t.Kind() {
case reflect.Bool:
if pointer {
return unmarshalBoolPtr
}
if slice {
return unmarshalBoolSlice
}
return unmarshalBoolValue
case reflect.Int32:
switch encoding {
case "fixed32":
if pointer {
return unmarshalFixedS32Ptr
}
if slice {
return unmarshalFixedS32Slice
}
return unmarshalFixedS32Value
case "varint":
// this could be int32 or enum
if pointer {
return unmarshalInt32Ptr
}
if slice {
return unmarshalInt32Slice
}
return unmarshalInt32Value
case "zigzag32":
if pointer {
return unmarshalSint32Ptr
}
if slice {
return unmarshalSint32Slice
}
return unmarshalSint32Value
}
case reflect.Int64:
switch encoding {
case "fixed64":
if pointer {
return unmarshalFixedS64Ptr
}
if slice {
return unmarshalFixedS64Slice
}
return unmarshalFixedS64Value
case "varint":
if pointer {
return unmarshalInt64Ptr
}
if slice {
return unmarshalInt64Slice
}
return unmarshalInt64Value
case "zigzag64":
if pointer {
return unmarshalSint64Ptr
}
if slice {
return unmarshalSint64Slice
}
return unmarshalSint64Value
}
case reflect.Uint32:
switch encoding {
case "fixed32":
if pointer {
return unmarshalFixed32Ptr
}
if slice {
return unmarshalFixed32Slice
}
return unmarshalFixed32Value
case "varint":
if pointer {
return unmarshalUint32Ptr
}
if slice {
return unmarshalUint32Slice
}
return unmarshalUint32Value
}
case reflect.Uint64:
switch encoding {
case "fixed64":
if pointer {
return unmarshalFixed64Ptr
}
if slice {
return unmarshalFixed64Slice
}
return unmarshalFixed64Value
case "varint":
if pointer {
return unmarshalUint64Ptr
}
if slice {
return unmarshalUint64Slice
}
return unmarshalUint64Value
}
case reflect.Float32:
if pointer {
return unmarshalFloat32Ptr
}
if slice {
return unmarshalFloat32Slice
}
return unmarshalFloat32Value
case reflect.Float64:
if pointer {
return unmarshalFloat64Ptr
}
if slice {
return unmarshalFloat64Slice
}
return unmarshalFloat64Value
case reflect.Map:
panic("map type in typeUnmarshaler in " + t.Name())
case reflect.Slice:
if pointer {
panic("bad pointer in slice case in " + t.Name())
}
if slice {
return unmarshalBytesSlice
}
return unmarshalBytesValue
case reflect.String:
if validateUTF8 {
if pointer {
return unmarshalUTF8StringPtr
}
if slice {
return unmarshalUTF8StringSlice
}
return unmarshalUTF8StringValue
}
if pointer {
return unmarshalStringPtr
}
if slice {
return unmarshalStringSlice
}
return unmarshalStringValue
case reflect.Struct:
// message or group field
if !pointer {
switch encoding {
case "bytes":
if slice {
return makeUnmarshalMessageSlice(getUnmarshalInfo(t), name)
}
return makeUnmarshalMessage(getUnmarshalInfo(t), name)
}
}
switch encoding {
case "bytes":
if slice {
return makeUnmarshalMessageSlicePtr(getUnmarshalInfo(t), name)
}
return makeUnmarshalMessagePtr(getUnmarshalInfo(t), name)
case "group":
if slice {
return makeUnmarshalGroupSlicePtr(getUnmarshalInfo(t), name)
}
return makeUnmarshalGroupPtr(getUnmarshalInfo(t), name)
}
}
panic(fmt.Sprintf("unmarshaler not found type:%s encoding:%s", t, encoding))
} | typeUnmarshaler returns an unmarshaler for the given field type / field tag pair. | typeUnmarshaler | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/table_unmarshal.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/table_unmarshal.go | Apache-2.0 |
func makeUnmarshalOneof(typ, ityp reflect.Type, unmarshal unmarshaler) unmarshaler {
sf := typ.Field(0)
field0 := toField(&sf)
return func(b []byte, f pointer, w int) ([]byte, error) {
// Allocate holder for value.
v := reflect.New(typ)
// Unmarshal data into holder.
// We unmarshal into the first field of the holder object.
var err error
var nerr nonFatal
b, err = unmarshal(b, valToPointer(v).offset(field0), w)
if !nerr.Merge(err) {
return nil, err
}
// Write pointer to holder into target field.
f.asPointerTo(ityp).Elem().Set(v)
return b, nerr.E
}
} | makeUnmarshalOneof makes an unmarshaler for oneof fields.
for:
message Msg {
oneof F {
int64 X = 1;
float64 Y = 2;
}
}
typ is the type of the concrete entry for a oneof case (e.g. Msg_X).
ityp is the interface type of the oneof field (e.g. isMsg_F).
unmarshal is the unmarshaler for the base type of the oneof case (e.g. int64).
Note that this function will be called once for each case in the oneof. | makeUnmarshalOneof | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/table_unmarshal.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/table_unmarshal.go | Apache-2.0 |
func skipField(b []byte, wire int) ([]byte, error) {
switch wire {
case WireVarint:
_, k := decodeVarint(b)
if k == 0 {
return b, io.ErrUnexpectedEOF
}
b = b[k:]
case WireFixed32:
if len(b) < 4 {
return b, io.ErrUnexpectedEOF
}
b = b[4:]
case WireFixed64:
if len(b) < 8 {
return b, io.ErrUnexpectedEOF
}
b = b[8:]
case WireBytes:
m, k := decodeVarint(b)
if k == 0 || uint64(len(b)-k) < m {
return b, io.ErrUnexpectedEOF
}
b = b[uint64(k)+m:]
case WireStartGroup:
_, i := findEndGroup(b)
if i == -1 {
return b, io.ErrUnexpectedEOF
}
b = b[i:]
default:
return b, fmt.Errorf("proto: can't skip unknown wire type %d", wire)
}
return b, nil
} | skipField skips past a field of type wire and returns the remaining bytes. | skipField | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/table_unmarshal.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/table_unmarshal.go | Apache-2.0 |
func findEndGroup(b []byte) (int, int) {
depth := 1
i := 0
for {
x, n := decodeVarint(b[i:])
if n == 0 {
return -1, -1
}
j := i
i += n
switch x & 7 {
case WireVarint:
_, k := decodeVarint(b[i:])
if k == 0 {
return -1, -1
}
i += k
case WireFixed32:
if len(b)-4 < i {
return -1, -1
}
i += 4
case WireFixed64:
if len(b)-8 < i {
return -1, -1
}
i += 8
case WireBytes:
m, k := decodeVarint(b[i:])
if k == 0 {
return -1, -1
}
i += k
if uint64(len(b)-i) < m {
return -1, -1
}
i += int(m)
case WireStartGroup:
depth++
case WireEndGroup:
depth--
if depth == 0 {
return j, i
}
default:
return -1, -1
}
}
} | findEndGroup finds the index of the next EndGroup tag.
Groups may be nested, so the "next" EndGroup tag is the first
unpaired EndGroup.
findEndGroup returns the indexes of the start and end of the EndGroup tag.
Returns (-1,-1) if it can't find one. | findEndGroup | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/table_unmarshal.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/table_unmarshal.go | Apache-2.0 |
func encodeVarint(b []byte, x uint64) []byte {
for x >= 1<<7 {
b = append(b, byte(x&0x7f|0x80))
x >>= 7
}
return append(b, byte(x))
} | encodeVarint appends a varint-encoded integer to b and returns the result. | encodeVarint | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/table_unmarshal.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/table_unmarshal.go | Apache-2.0 |
func decodeVarint(b []byte) (uint64, int) {
var x, y uint64
if len(b) == 0 {
goto bad
}
x = uint64(b[0])
if x < 0x80 {
return x, 1
}
x -= 0x80
if len(b) <= 1 {
goto bad
}
y = uint64(b[1])
x += y << 7
if y < 0x80 {
return x, 2
}
x -= 0x80 << 7
if len(b) <= 2 {
goto bad
}
y = uint64(b[2])
x += y << 14
if y < 0x80 {
return x, 3
}
x -= 0x80 << 14
if len(b) <= 3 {
goto bad
}
y = uint64(b[3])
x += y << 21
if y < 0x80 {
return x, 4
}
x -= 0x80 << 21
if len(b) <= 4 {
goto bad
}
y = uint64(b[4])
x += y << 28
if y < 0x80 {
return x, 5
}
x -= 0x80 << 28
if len(b) <= 5 {
goto bad
}
y = uint64(b[5])
x += y << 35
if y < 0x80 {
return x, 6
}
x -= 0x80 << 35
if len(b) <= 6 {
goto bad
}
y = uint64(b[6])
x += y << 42
if y < 0x80 {
return x, 7
}
x -= 0x80 << 42
if len(b) <= 7 {
goto bad
}
y = uint64(b[7])
x += y << 49
if y < 0x80 {
return x, 8
}
x -= 0x80 << 49
if len(b) <= 8 {
goto bad
}
y = uint64(b[8])
x += y << 56
if y < 0x80 {
return x, 9
}
x -= 0x80 << 56
if len(b) <= 9 {
goto bad
}
y = uint64(b[9])
x += y << 63
if y < 2 {
return x, 10
}
bad:
return 0, 0
} | decodeVarint reads a varint-encoded integer from b.
Returns the decoded integer and the number of bytes read.
If there is an error, it returns 0,0. | decodeVarint | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/table_unmarshal.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/table_unmarshal.go | Apache-2.0 |
func toField(f *reflect.StructField) field {
return f.Index
} | toField returns a field equivalent to the given reflect field. | toField | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/pointer_reflect.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/pointer_reflect.go | Apache-2.0 |
func (f field) IsValid() bool { return f != nil } | IsValid reports whether the field identifier is valid. | IsValid | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/pointer_reflect.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/pointer_reflect.go | Apache-2.0 |
func toPointer(i *Message) pointer {
return pointer{v: reflect.ValueOf(*i)}
} | toPointer converts an interface of pointer type to a pointer
that points to the same target. | toPointer | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/pointer_reflect.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/pointer_reflect.go | Apache-2.0 |
func toAddrPointer(i *interface{}, isptr bool) pointer {
v := reflect.ValueOf(*i)
u := reflect.New(v.Type())
u.Elem().Set(v)
return pointer{v: u}
} | toAddrPointer converts an interface to a pointer that points to
the interface data. | toAddrPointer | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/pointer_reflect.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/pointer_reflect.go | Apache-2.0 |
func valToPointer(v reflect.Value) pointer {
return pointer{v: v}
} | valToPointer converts v to a pointer. v must be of pointer type. | valToPointer | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/pointer_reflect.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/pointer_reflect.go | Apache-2.0 |
func (p pointer) offset(f field) pointer {
return pointer{v: p.v.Elem().FieldByIndex(f).Addr()}
} | offset converts from a pointer to a structure to a pointer to
one of its fields. | offset | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/pointer_reflect.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/pointer_reflect.go | Apache-2.0 |
func grow(s reflect.Value) reflect.Value {
n, m := s.Len(), s.Cap()
if n < m {
s.SetLen(n + 1)
} else {
s.Set(reflect.Append(s, reflect.Zero(s.Type().Elem())))
}
return s.Index(n)
} | grow updates the slice s in place to make it one element longer.
s must be addressable.
Returns the (addressable) new element. | grow | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/pointer_reflect.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/pointer_reflect.go | Apache-2.0 |
func (p pointer) getInt32Slice() []int32 {
if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) {
// raw int32 type
return p.v.Elem().Interface().([]int32)
}
// an enum
// Allocate a []int32, then assign []enum's values into it.
// Note: we can't convert []enum to []int32.
slice := p.v.Elem()
s := make([]int32, slice.Len())
for i := 0; i < slice.Len(); i++ {
s[i] = int32(slice.Index(i).Int())
}
return s
} | getInt32Slice copies []int32 from p as a new slice.
This behavior differs from the implementation in pointer_unsafe.go. | getInt32Slice | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/pointer_reflect.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/pointer_reflect.go | Apache-2.0 |
func (p pointer) setInt32Slice(v []int32) {
if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) {
// raw int32 type
p.v.Elem().Set(reflect.ValueOf(v))
return
}
// an enum
// Allocate a []enum, then assign []int32's values into it.
// Note: we can't convert []enum to []int32.
slice := reflect.MakeSlice(p.v.Type().Elem(), len(v), cap(v))
for i, x := range v {
slice.Index(i).SetInt(int64(x))
}
p.v.Elem().Set(slice)
} | setInt32Slice copies []int32 into p as a new slice.
This behavior differs from the implementation in pointer_unsafe.go. | setInt32Slice | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/pointer_reflect.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/pointer_reflect.go | Apache-2.0 |
func (p pointer) getPointerSlice() []pointer {
if p.v.IsNil() {
return nil
}
n := p.v.Elem().Len()
s := make([]pointer, n)
for i := 0; i < n; i++ {
s[i] = pointer{v: p.v.Elem().Index(i)}
}
return s
} | getPointerSlice copies []*T from p as a new []pointer.
This behavior differs from the implementation in pointer_unsafe.go. | getPointerSlice | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/pointer_reflect.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/pointer_reflect.go | Apache-2.0 |
func (p pointer) setPointerSlice(v []pointer) {
if v == nil {
p.v.Elem().Set(reflect.New(p.v.Elem().Type()).Elem())
return
}
s := reflect.MakeSlice(p.v.Elem().Type(), 0, len(v))
for _, p := range v {
s = reflect.Append(s, p.v)
}
p.v.Elem().Set(s)
} | setPointerSlice copies []pointer into p as a new []*T.
This behavior differs from the implementation in pointer_unsafe.go. | setPointerSlice | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/pointer_reflect.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/pointer_reflect.go | Apache-2.0 |
func (p pointer) getInterfacePointer() pointer {
if p.v.Elem().IsNil() {
return pointer{v: p.v.Elem()}
}
return pointer{v: p.v.Elem().Elem().Elem().Field(0).Addr()} // *interface -> interface -> *struct -> struct
} | getInterfacePointer returns a pointer that points to the
interface data of the interface pointed by p. | getInterfacePointer | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/pointer_reflect.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/pointer_reflect.go | Apache-2.0 |
func extendable(p interface{}) (extendableProto, error) {
switch p := p.(type) {
case extendableProto:
if isNilPtr(p) {
return nil, fmt.Errorf("proto: nil %T is not extendable", p)
}
return p, nil
case extendableProtoV1:
if isNilPtr(p) {
return nil, fmt.Errorf("proto: nil %T is not extendable", p)
}
return extensionAdapter{p}, nil
case extensionsBytes:
return slowExtensionAdapter{p}, nil
} | extendable returns the extendableProto interface for the given generated proto message.
If the proto message has the old extension format, it returns a wrapper that implements
the extendableProto interface. | extendable | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/extensions.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/extensions.go | Apache-2.0 |
func SetRawExtension(base Message, id int32, b []byte) {
if ebase, ok := base.(extensionsBytes); ok {
clearExtension(base, id)
ext := ebase.GetExtensions()
*ext = append(*ext, b...)
return
}
epb, err := extendable(base)
if err != nil {
return
}
extmap := epb.extensionsWrite()
extmap[id] = Extension{enc: b}
} | SetRawExtension is for testing only. | SetRawExtension | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/extensions.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/extensions.go | Apache-2.0 |
func isExtensionField(pb extendableProto, field int32) bool {
for _, er := range pb.ExtensionRangeArray() {
if er.Start <= field && field <= er.End {
return true
}
}
return false
} | isExtensionField returns true iff the given field number is in an extension range. | isExtensionField | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/extensions.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/extensions.go | Apache-2.0 |
func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error {
var pbi interface{} = pb
// Check the extended type.
if ea, ok := pbi.(extensionAdapter); ok {
pbi = ea.extendableProtoV1
}
if ea, ok := pbi.(slowExtensionAdapter); ok {
pbi = ea.extensionsBytes
}
if a, b := reflect.TypeOf(pbi), reflect.TypeOf(extension.ExtendedType); a != b {
return fmt.Errorf("proto: bad extended type; %v does not extend %v", b, a)
}
// Check the range.
if !isExtensionField(pb, extension.Field) {
return errors.New("proto: bad extension number; not in declared ranges")
}
return nil
} | checkExtensionTypes checks that the given extension is valid for pb. | checkExtensionTypes | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/extensions.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/extensions.go | Apache-2.0 |
func HasExtension(pb Message, extension *ExtensionDesc) bool {
if epb, doki := pb.(extensionsBytes); doki {
ext := epb.GetExtensions()
buf := *ext
o := 0
for o < len(buf) {
tag, n := DecodeVarint(buf[o:])
fieldNum := int32(tag >> 3)
if int32(fieldNum) == extension.Field {
return true
}
wireType := int(tag & 0x7)
o += n
l, err := size(buf[o:], wireType)
if err != nil {
return false
}
o += l
}
return false
}
// TODO: Check types, field numbers, etc.?
epb, err := extendable(pb)
if err != nil {
return false
}
extmap, mu := epb.extensionsRead()
if extmap == nil {
return false
}
mu.Lock()
_, ok := extmap[extension.Field]
mu.Unlock()
return ok
} | HasExtension returns whether the given extension is present in pb. | HasExtension | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/extensions.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/extensions.go | Apache-2.0 |
func ClearExtension(pb Message, extension *ExtensionDesc) {
clearExtension(pb, extension.Field)
} | ClearExtension removes the given extension from pb. | ClearExtension | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/extensions.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/extensions.go | Apache-2.0 |
func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error) {
if epb, doki := pb.(extensionsBytes); doki {
ext := epb.GetExtensions()
return decodeExtensionFromBytes(extension, *ext)
}
epb, err := extendable(pb)
if err != nil {
return nil, err
}
if extension.ExtendedType != nil {
// can only check type if this is a complete descriptor
if cerr := checkExtensionTypes(epb, extension); cerr != nil {
return nil, cerr
}
}
emap, mu := epb.extensionsRead()
if emap == nil {
return defaultExtensionValue(extension)
}
mu.Lock()
defer mu.Unlock()
e, ok := emap[extension.Field]
if !ok {
// defaultExtensionValue returns the default value or
// ErrMissingExtension if there is no default.
return defaultExtensionValue(extension)
}
if e.value != nil {
// Already decoded. Check the descriptor, though.
if e.desc != extension {
// This shouldn't happen. If it does, it means that
// GetExtension was called twice with two different
// descriptors with the same field number.
return nil, errors.New("proto: descriptor conflict")
}
return e.value, nil
}
if extension.ExtensionType == nil {
// incomplete descriptor
return e.enc, nil
}
v, err := decodeExtension(e.enc, extension)
if err != nil {
return nil, err
}
// Remember the decoded version and drop the encoded version.
// That way it is safe to mutate what we return.
e.value = v
e.desc = extension
e.enc = nil
emap[extension.Field] = e
return e.value, nil
} | GetExtension retrieves a proto2 extended field from pb.
If the descriptor is type complete (i.e., ExtensionDesc.ExtensionType is non-nil),
then GetExtension parses the encoded field and returns a Go value of the specified type.
If the field is not present, then the default value is returned (if one is specified),
otherwise ErrMissingExtension is reported.
If the descriptor is not type complete (i.e., ExtensionDesc.ExtensionType is nil),
then GetExtension returns the raw encoded bytes of the field extension. | GetExtension | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/extensions.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/extensions.go | Apache-2.0 |
func defaultExtensionValue(extension *ExtensionDesc) (interface{}, error) {
if extension.ExtensionType == nil {
// incomplete descriptor, so no default
return nil, ErrMissingExtension
}
t := reflect.TypeOf(extension.ExtensionType)
props := extensionProperties(extension)
sf, _, err := fieldDefault(t, props)
if err != nil {
return nil, err
}
if sf == nil || sf.value == nil {
// There is no default value.
return nil, ErrMissingExtension
}
if t.Kind() != reflect.Ptr {
// We do not need to return a Ptr, we can directly return sf.value.
return sf.value, nil
}
// We need to return an interface{} that is a pointer to sf.value.
value := reflect.New(t).Elem()
value.Set(reflect.New(value.Type().Elem()))
if sf.kind == reflect.Int32 {
// We may have an int32 or an enum, but the underlying data is int32.
// Since we can't set an int32 into a non int32 reflect.value directly
// set it as a int32.
value.Elem().SetInt(int64(sf.value.(int32)))
} else {
value.Elem().Set(reflect.ValueOf(sf.value))
}
return value.Interface(), nil
} | defaultExtensionValue returns the default value for extension.
If no default for an extension is defined ErrMissingExtension is returned. | defaultExtensionValue | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/extensions.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/extensions.go | Apache-2.0 |
func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) {
t := reflect.TypeOf(extension.ExtensionType)
unmarshal := typeUnmarshaler(t, extension.Tag)
// t is a pointer to a struct, pointer to basic type or a slice.
// Allocate space to store the pointer/slice.
value := reflect.New(t).Elem()
var err error
for {
x, n := decodeVarint(b)
if n == 0 {
return nil, io.ErrUnexpectedEOF
}
b = b[n:]
wire := int(x) & 7
b, err = unmarshal(b, valToPointer(value.Addr()), wire)
if err != nil {
return nil, err
}
if len(b) == 0 {
break
}
}
return value.Interface(), nil
} | decodeExtension decodes an extension encoded in b. | decodeExtension | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/extensions.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/extensions.go | Apache-2.0 |
func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) {
epb, err := extendable(pb)
if err != nil {
return nil, err
}
extensions = make([]interface{}, len(es))
for i, e := range es {
extensions[i], err = GetExtension(epb, e)
if err == ErrMissingExtension {
err = nil
}
if err != nil {
return
}
}
return
} | GetExtensions returns a slice of the extensions present in pb that are also listed in es.
The returned slice has the same length as es; missing extensions will appear as nil elements. | GetExtensions | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/extensions.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/extensions.go | Apache-2.0 |
func ExtensionDescs(pb Message) ([]*ExtensionDesc, error) {
epb, err := extendable(pb)
if err != nil {
return nil, err
}
registeredExtensions := RegisteredExtensions(pb)
emap, mu := epb.extensionsRead()
if emap == nil {
return nil, nil
}
mu.Lock()
defer mu.Unlock()
extensions := make([]*ExtensionDesc, 0, len(emap))
for extid, e := range emap {
desc := e.desc
if desc == nil {
desc = registeredExtensions[extid]
if desc == nil {
desc = &ExtensionDesc{Field: extid}
}
}
extensions = append(extensions, desc)
}
return extensions, nil
} | ExtensionDescs returns a new slice containing pb's extension descriptors, in undefined order.
For non-registered extensions, ExtensionDescs returns an incomplete descriptor containing
just the Field field, which defines the extension's field number. | ExtensionDescs | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/extensions.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/extensions.go | Apache-2.0 |
func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error {
if epb, ok := pb.(extensionsBytes); ok {
ClearExtension(pb, extension)
newb, err := encodeExtension(extension, value)
if err != nil {
return err
}
bb := epb.GetExtensions()
*bb = append(*bb, newb...)
return nil
}
epb, err := extendable(pb)
if err != nil {
return err
}
if err := checkExtensionTypes(epb, extension); err != nil {
return err
}
typ := reflect.TypeOf(extension.ExtensionType)
if typ != reflect.TypeOf(value) {
return fmt.Errorf("proto: bad extension value type. got: %T, want: %T", value, extension.ExtensionType)
}
// nil extension values need to be caught early, because the
// encoder can't distinguish an ErrNil due to a nil extension
// from an ErrNil due to a missing field. Extensions are
// always optional, so the encoder would just swallow the error
// and drop all the extensions from the encoded message.
if reflect.ValueOf(value).IsNil() {
return fmt.Errorf("proto: SetExtension called with nil value of type %T", value)
}
extmap := epb.extensionsWrite()
extmap[extension.Field] = Extension{desc: extension, value: value}
return nil
} | SetExtension sets the specified extension of pb to the specified value. | SetExtension | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/extensions.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/extensions.go | Apache-2.0 |
func ClearAllExtensions(pb Message) {
if epb, doki := pb.(extensionsBytes); doki {
ext := epb.GetExtensions()
*ext = []byte{}
return
}
epb, err := extendable(pb)
if err != nil {
return
}
m := epb.extensionsWrite()
for k := range m {
delete(m, k)
}
} | ClearAllExtensions clears all extensions from pb. | ClearAllExtensions | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/extensions.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/extensions.go | Apache-2.0 |
func RegisterExtension(desc *ExtensionDesc) {
st := reflect.TypeOf(desc.ExtendedType).Elem()
m := extensionMaps[st]
if m == nil {
m = make(map[int32]*ExtensionDesc)
extensionMaps[st] = m
}
if _, ok := m[desc.Field]; ok {
panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field)))
}
m[desc.Field] = desc
} | RegisterExtension is called from the generated code. | RegisterExtension | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/extensions.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/extensions.go | Apache-2.0 |
func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc {
return extensionMaps[reflect.TypeOf(pb).Elem()]
} | RegisteredExtensions returns a map of the registered extensions of a
protocol buffer struct, indexed by the extension number.
The argument pb should be a nil pointer to the struct type. | RegisteredExtensions | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/extensions.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/extensions.go | Apache-2.0 |
func Clone(src Message) Message {
in := reflect.ValueOf(src)
if in.IsNil() {
return src
}
out := reflect.New(in.Type().Elem())
dst := out.Interface().(Message)
Merge(dst, src)
return dst
} | Clone returns a deep copy of a protocol buffer. | Clone | go | k8snetworkplumbingwg/multus-cni | vendor/github.com/gogo/protobuf/proto/clone.go | https://github.com/k8snetworkplumbingwg/multus-cni/blob/master/vendor/github.com/gogo/protobuf/proto/clone.go | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.