policy/acl/aclbit.go
2023-03-31 23:30:20 +10:00

150 lines
2.2 KiB
Go

package acl
import (
"fmt"
"strconv"
)
type NumBit int64
type AclBit int64
const (
AllBit AclBit = 9223372036854775807
)
// New AclBit
func New(n ...NumBit) (a AclBit) {
a.SetTrue(n...)
return a
}
// unite slice int to int64
func Unite(a ...AclBit) AclBit {
var endacl AclBit
for _, a0 := range a {
endacl = endacl | a0
}
return endacl
}
// set acl bit in true
func (a *AclBit) SetTrue(n ...NumBit) {
for _, n0 := range n {
if veryNumBit(n0) {
*a = *a | (1 << n0)
}
}
}
// set acl bit in false
func (a *AclBit) SetFalse(n ...NumBit) {
for _, n0 := range n {
if veryNumBit(n0) {
*a = *a &^ (1 << n0)
}
}
}
// verify bit return true or false
func (a AclBit) Verify(n NumBit) bool {
if veryNumBit(n) {
var msk AclBit = 1 << n
if (a & msk) == msk {
return true
}
}
return false
}
// verify mask return true or false
func (a AclBit) VerifyMask(mask AclBit) bool {
if (a & mask) > 0 {
return true
}
return false
}
// parsing AlcBit to array NumBit
func (a AclBit) Parse() []NumBit {
var n []NumBit
for i := 0; i < 63; i++ {
if a.Verify(NumBit(i)) {
n = append(n, NumBit(i))
}
}
return n
}
// verify or bit return true or false
func (a AclBit) VerifyOr(n ...NumBit) bool {
for _, n0 := range n {
if a.Verify(n0) {
return true
}
}
return false
}
// verify and bit return true or false
func (a AclBit) VerifyAnd(n ...NumBit) bool {
for _, n0 := range n {
if !a.Verify(n0) {
return false
}
}
return true
}
// converting acl bits to string
func (a AclBit) String() string {
return strconv.FormatInt(int64(a), 2)
}
// converting string bits to int64
func (a AclBit) Int64() int64 {
return int64(a)
}
// converting string bits to int64
func Int64(i any) int64 {
var i64 int64
var err error
switch i.(type) {
case string:
str := fmt.Sprintf("%s", i)
i64, err = strconv.ParseInt(str, 2, 64)
if err != nil {
return -1
}
return i64
case AclBit:
i64 = int64(i.(AclBit))
return i64
case int64:
i64 = i.(int64)
return i64
case uint64:
i64 = int64(i.(uint64))
return i64
default:
i64 = -1
return i64
}
}
// verytify Num bit (max range 0 - 62 , summary 63 bit)
func veryNumBit(n NumBit) bool {
if n >= 0 && n < 63 {
return true
}
return false
}