bitmap

package
v0.7.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 10, 2026 License: Apache-2.0 Imports: 1 Imported by: 0

Documentation

Overview

Package bitmap 提供位图:用 1 bit 表示一个布尔状态,极省内存的大规模标记与集合运算。

典型:

  • 签到:每天一张 bitmap,第 i 位=用户 i 是否签到——1000 万用户仅需 ~1.25MB/天; 多天 bitmap 做 And 可算"连续签到",Count 算"当日签到数";
  • 去重 / 存在性标记:第 i 位=ID i 是否出现过(ID 稠密时比 map 省几十倍内存);
  • 权限位 / 特征位:一个整数装不下时用 bitmap 表示大量开关。

与 pkg/utils/bloom 的区别:bloom 是概率型(有假阳性、省内存、不可枚举),用于 "可能存在"的快速判断;bitmap 是精确型(位与 ID 一一对应,可精确 Count/枚举), 用于 ID 稠密、需要精确计数与集合运算的场景。

底层 []uint64,按需增长。非并发安全(读多写少可在上层加锁;或每个写者独占一张)。 零值可用(空位图),也可用 New 预分配。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConsecutiveFromEnd

func ConsecutiveFromEnd(days []*Bitmap, uid int) int

ConsecutiveFromEnd 对一组"按时间顺序"的每日签到位图,返回用户 uid 从最后一天 往前数的连续签到天数(最后一天未签到则为 0)。days 顺序:days[len-1] 为最新一天。

例:days = [周一,周二,周三],uid 在周二、周三签到 → 从末尾连续 2 天。

Types

type Bitmap

type Bitmap struct {
	// contains filtered or unexported fields
}

Bitmap 是一个可增长的位图。零值可用。非并发安全。

func New

func New(n int) *Bitmap

New 创建一个至少能容纳 [0, n) 位的位图(预分配,避免增长时的多次分配)。

func (*Bitmap) And

func (b *Bitmap) And(other *Bitmap) *Bitmap

And 就地与另一位图求交(自身 = 自身 ∩ other),返回自身以便链式。

func (*Bitmap) AndNot

func (b *Bitmap) AndNot(other *Bitmap) *Bitmap

AndNot 就地求差(自身 = 自身 \ other,清掉 other 中为 1 的位),返回自身。

func (*Bitmap) Clear

func (b *Bitmap) Clear(i int)

Clear 清位 i(设为 0)。越界/负数忽略。

func (*Bitmap) Clone

func (b *Bitmap) Clone() *Bitmap

Clone 返回位图的深拷贝。

func (*Bitmap) Count

func (b *Bitmap) Count() int

Count 返回置为 1 的位总数(popcount,O(words))。

func (*Bitmap) Flip

func (b *Bitmap) Flip(i int) bool

Flip 翻转位 i,返回翻转后的值。越界自动增长。

func (*Bitmap) Or

func (b *Bitmap) Or(other *Bitmap) *Bitmap

Or 就地与另一位图求并(自身 = 自身 ∪ other),返回自身。

func (*Bitmap) Reset

func (b *Bitmap) Reset()

Reset 清空所有位(容量保留)。

func (*Bitmap) Set

func (b *Bitmap) Set(i int)

Set 置位 i(设为 1)。i 越界会自动增长。i<0 忽略。

func (*Bitmap) Slice

func (b *Bitmap) Slice() []int

Slice 返回所有置 1 位的下标(升序)。用于枚举(如"当日签到的用户 ID 列表")。

func (*Bitmap) Test

func (b *Bitmap) Test(i int) bool

Test 返回位 i 是否为 1。越界/负数返回 false。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL