// ------------------------------------------------------------------------ // Project atila // Active Thing (activething.com) git.activething.com/go // // File name bflag.go // Created by DEV // Modified 15/02/2024 // // Copyright 2024 activething.com // ------------------------------------------------------------------------ // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------ package bits import ( "atypes" "encoding/binary" "math/bits" ) func Has [T atypes.UnsignedAll](source T, flag T) bool { return source&flag != 0 } func Add [T atypes.UnsignedAll](source T, flag T) T { return source|flag } func AddWithMask [T atypes.UnsignedAll](source T, flag T, mask T) T { return (source&mask) | flag } func Del [T atypes.UnsignedAll](source T, flag T) T { return source&^flag } func Invert [T atypes.UnsignedAll](source T) T { return ^source } func Count[T atypes.UnsignedAll](source T) int { switch binary.Size(source) { case 1 : return bits.OnesCount8 (uint8(source)) case 2 : return bits.OnesCount16(uint16(source)) case 4 : return bits.OnesCount32(uint32(source)) case 8 : return bits.OnesCount64(uint64(source)) default: panic(G.ErrUnsupportedFlagType) } } func Extract[T atypes.UnsignedAll](source T) []T { if source == 0 { return []T{} } l := make([]T,0,16) c := T(1) for i:=1; i<= 7; i++ { if c&source == c { l = append(l,c) } c <<= 1 } return l } func FlagsToNames [T atypes.UnsignedAll](source T, namer func(flags T) string) []string { if source == 0 { return []string{} } l := make([]string,0,16) c := T(1) for i:=1; i<= 7; i++ { if c&source == c { l = append(l,namer(c)) } c <<= 1 } return l } func NamesToFlags [T atypes.UnsignedAll](names []string, flagger func(name string) T) T { var f T for _,s := range names { f|=flagger(s) } return f }