Debian Codegraph @

pkg/types/internal/create.go

raw
1 // Copyright 2016 CNI authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package convert
16
17 import (
18 "fmt"
19
20 "github.com/containernetworking/cni/pkg/types"
21 )
22
23 type ResultFactoryFunc func([]byte) (types.Result, error)
24
25 type creator struct {
26 // CNI Result spec versions that createFn can create a Result for
27 versions []string
28 createFn ResultFactoryFunc
29 }
30
31 var creators []*creator
32
33 func findCreator(version string) *creator {
34 for _, c := range creators {
35 for _, v := range c.versions {
36 if v == version {
37 return c
38 }
39 }
40 }
41 return nil
42 }
43
44 // Create creates a CNI Result using the given JSON, or an error if the creation
45 // could not be performed
46 func Create(version string, bytes []byte) (types.Result, error) {
47 if c := findCreator(version); c != nil {
48 return c.createFn(bytes)
49 }
50 return nil, fmt.Errorf("unsupported CNI result version %q", version)
51 }
52
53 // RegisterCreator registers a CNI Result creator. SHOULD NOT BE CALLED
54 // EXCEPT FROM CNI ITSELF.
55 func RegisterCreator(versions []string, createFn ResultFactoryFunc) {
56 // Make sure there is no creator already registered for these versions
57 for _, v := range versions {
58 if findCreator(v) != nil {
59 panic(fmt.Sprintf("creator already registered for %s", v))
60 }
61 }
62 creators = append(creators, &creator{
63 versions: versions,
64 createFn: createFn,
65 })
66 }