github.com/cilium/cilium@v1.16.2/pkg/policy/api/decision.go (about) 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright Authors of Cilium 3 4 package api 5 6 import ( 7 "fmt" 8 ) 9 10 // Decision is a reachability policy decision 11 type Decision byte 12 13 const ( 14 // Undecided means that we have not come to a decision yet 15 Undecided Decision = iota 16 // Allowed means that reachability is allowed 17 Allowed 18 // Denied means that reachability is denied 19 Denied 20 ) 21 22 var ( 23 decisionToString = map[Decision]string{ 24 Undecided: "undecided", 25 Allowed: "allowed", 26 Denied: "denied", 27 } 28 stringToDecision = map[string]Decision{ 29 "undecided": Undecided, 30 "allowed": Allowed, 31 "denied": Denied, 32 } 33 ) 34 35 // String returns the decision in human readable format 36 func (d Decision) String() string { 37 if v, exists := decisionToString[d]; exists { 38 return v 39 } 40 return "" 41 } 42 43 // UnmarshalJSON parses a JSON formatted buffer and returns a decision 44 func (d *Decision) UnmarshalJSON(b []byte) error { 45 if d == nil { 46 d = new(Decision) 47 } 48 if len(b) <= len(`""`) { 49 return fmt.Errorf("invalid decision '%s'", string(b)) 50 } 51 if v, exists := stringToDecision[string(b[1:len(b)-1])]; exists { 52 *d = v 53 return nil 54 } 55 56 return fmt.Errorf("unknown '%s' decision", string(b)) 57 } 58 59 // MarshalJSON returns the decision as JSON formatted buffer 60 func (d Decision) MarshalJSON() ([]byte, error) { 61 s := d.String() 62 // length of decision string plus two `"` 63 b := make([]byte, len(s)+2) 64 b[0] = '"' 65 copy(b[1:], s) 66 b[len(b)-1] = '"' 67 return b, nil 68 }