github.com/rkt/rkt@v1.30.1-0.20200224141603-171c416fac02/pkg/flag/bitflags.go (about)

     1  // Copyright 2015 The rkt 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 flag
    16  
    17  import (
    18  	"errors"
    19  	"fmt"
    20  
    21  	"github.com/hashicorp/errwrap"
    22  )
    23  
    24  // BitFlags is a flag value type supporting a csv list of options stored as bits
    25  type BitFlags struct {
    26  	*OptionList
    27  	Flags   int
    28  	FlagMap map[string]int
    29  }
    30  
    31  // NewBitFlags initializes a simple bitflag version of the OptionList Type.
    32  // flagMap is the mapping from option names to the integer value
    33  func NewBitFlags(permissibleOptions []string, defaultOptions string, flagMap map[string]int) (*BitFlags, error) {
    34  	ol, err := NewOptionList(permissibleOptions, defaultOptions)
    35  	if err != nil {
    36  		return nil, err
    37  	}
    38  
    39  	bf := &BitFlags{
    40  		OptionList: ol,
    41  		FlagMap:    flagMap,
    42  	}
    43  	bf.typeName = "BitFlags"
    44  
    45  	if err := bf.Set(defaultOptions); err != nil {
    46  		return nil, errwrap.Wrap(errors.New("problem setting defaults"), err)
    47  	}
    48  
    49  	return bf, nil
    50  }
    51  
    52  func (bf *BitFlags) Set(s string) error {
    53  	if err := bf.OptionList.Set(s); err != nil {
    54  		return err
    55  	}
    56  	bf.Flags = 0
    57  	for _, o := range bf.Options {
    58  		if b, ok := bf.FlagMap[o]; ok {
    59  			bf.Flags |= b
    60  		} else {
    61  			return fmt.Errorf("couldn't find flag for %v", o)
    62  		}
    63  	}
    64  	return nil
    65  }
    66  
    67  func (bf *BitFlags) HasFlag(f int) bool {
    68  	return (bf.Flags & f) == f
    69  }