From 38cc3129ba15d4ff7f06782c74d990834bbc0471 Mon Sep 17 00:00:00 2001 From: kercylan98 Date: Wed, 13 Dec 2023 17:07:57 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20super=20=E5=8C=85=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E6=AF=94=E7=89=B9=E6=8E=A9=E7=A0=81=E7=B1=BB=E5=9E=8B=20BitMas?= =?UTF-8?q?k=EF=BC=8C=E5=8F=AF=E9=80=9A=E8=BF=87=20super.Mask=20=E5=87=BD?= =?UTF-8?q?=E6=95=B0=E5=88=9B=E5=BB=BA=E3=80=82=E8=AF=A5=E7=B1=BB=E5=9E=8B?= =?UTF-8?q?=E5=8F=AF=E6=9B=BF=E4=BB=A3=20super.Permission?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utils/super/mask.go | 96 ++++++++++++++++++++++++++++++++++++++++ utils/super/mask_test.go | 16 +++++++ 2 files changed, 112 insertions(+) create mode 100644 utils/super/mask.go create mode 100644 utils/super/mask_test.go diff --git a/utils/super/mask.go b/utils/super/mask.go new file mode 100644 index 0000000..982ab43 --- /dev/null +++ b/utils/super/mask.go @@ -0,0 +1,96 @@ +package super + +import ( + "github.com/kercylan98/minotaur/utils/generic" + "math/bits" + "strconv" +) + +// BitMask 使用泛型类型 Bit 表示一个比特掩码,Bit 必须是整数类型。 +type BitMask[Bit generic.Integer] uint64 + +// Mask 创建一个新的 BitMask,包含给定的比特位。 +// 参数 bits 是一个可变参数列表,表示要设置的比特位。 +// - 使用按位或运算符 (|=) 将 bit 位置的比特设置为 1。 +func Mask[Bit generic.Integer](bits ...Bit) BitMask[Bit] { + var mask Bit + for _, bit := range bits { + mask |= 1 << bit + } + return BitMask[Bit](mask) +} + +// Matches 检查当前 BitMask 是否与另一个 BitMask 完全匹配。 +func (slf *BitMask[Bit]) Matches(bits BitMask[Bit]) bool { + return *slf == bits +} + +// Contains 检查当前 BitMask 是否包含另一个 BitMask。 +// - 使用按位与运算符 (&) 计算两个 BitMask 的公共部分,然后与 bits 进行比较。 +func (slf *BitMask[Bit]) Contains(bits BitMask[Bit]) bool { + return (*slf & bits) == bits +} + +// Has 检查当前 BitMask 是否包含特定的比特位。 +// - 使用按位与运算符 (&) 检查 bit 位置的比特是否为 1。 +func (slf *BitMask[Bit]) Has(bits ...Bit) bool { + for _, bit := range bits { + if *slf&(1<