github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/pkg/bits/bits_template.go (about)

     1  // Copyright 2018 The gVisor 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 bits
    16  
    17  // Non-atomic bit operations on a template type T.
    18  
    19  // T is a required type parameter that must be an integral type.
    20  type T uint64
    21  
    22  // IsOn returns true if *all* bits set in 'bits' are set in 'mask'.
    23  func IsOn(mask, bits T) bool {
    24  	return mask&bits == bits
    25  }
    26  
    27  // IsAnyOn returns true if *any* bit set in 'bits' is set in 'mask'.
    28  func IsAnyOn(mask, bits T) bool {
    29  	return mask&bits != 0
    30  }
    31  
    32  // Mask returns a T with all of the given bits set.
    33  func Mask(is ...int) T {
    34  	ret := T(0)
    35  	for _, i := range is {
    36  		ret |= MaskOf(i)
    37  	}
    38  	return ret
    39  }
    40  
    41  // MaskOf is like Mask, but sets only a single bit (more efficiently).
    42  func MaskOf(i int) T {
    43  	return T(1) << T(i)
    44  }
    45  
    46  // IsPowerOfTwo returns true if v is power of 2.
    47  func IsPowerOfTwo(v T) bool {
    48  	if v == 0 {
    49  		return false
    50  	}
    51  	return v&(v-1) == 0
    52  }