-
Gabriel Zachmann authoredGabriel Zachmann authored
singleasciiencode.go 2.73 KiB
package singleasciiencode
import (
log "github.com/sirupsen/logrus"
"github.com/oidc-mytoken/server/shared/utils"
)
const maxFlags = 6
// NewFlagEncoder creates a new FlagEncoder
func NewFlagEncoder() *FlagEncoder {
return &FlagEncoder{}
}
// FlagEncoder is type for encoding multiple binary (bool) flags into a single character
type FlagEncoder struct {
names [maxFlags]string
f [maxFlags]bool
nextIndex int
}
// Set sets a name value pair that should be encoded
func (fe *FlagEncoder) Set(name string, value bool) bool {
for i, n := range fe.names {
if i >= fe.nextIndex {
break
}
if n == name {
fe.f[i] = value
return true
}
}
if fe.nextIndex >= maxFlags {
return false
}
fe.names[fe.nextIndex] = name
fe.f[fe.nextIndex] = value
fe.nextIndex++
return true
}
// Sets sets multiple name values
func (fe *FlagEncoder) Sets(values map[string]bool) bool {
names := []string{}
for n := range values {
names = append(names, n)
}
commonNames := len(utils.IntersectSlices(names, fe.names[:]))
if maxFlags-fe.nextIndex < len(values)-commonNames { // If we cannot set all values, abort
return false
}
for n, v := range values {
if set := fe.Set(n, v); !set {
return false
}
}
return true
}
// Get returns the value for a given name
func (fe FlagEncoder) Get(name string) (value, found bool) {
var index int
var n string
for index, n = range fe.names {
if n == name {
found = true
break
}
}