Initial commit (code only without large binaries)

This commit is contained in:
robin
2026-02-15 18:58:44 +08:00
commit 35df75498f
9442 changed files with 1495866 additions and 0 deletions

View File

@@ -0,0 +1,66 @@
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
package setutils
import (
"github.com/TeaOSLab/EdgeNode/internal/utils/zero"
"sync"
)
// FixedSet
// TODO 解决已存在元素不能按顺序弹出的问题
type FixedSet struct {
maxSize int
locker sync.RWMutex
m map[any]zero.Zero
keys []any
}
func NewFixedSet(maxSize int) *FixedSet {
if maxSize <= 0 {
maxSize = 1024
}
return &FixedSet{
maxSize: maxSize,
m: map[any]zero.Zero{},
}
}
func (this *FixedSet) Push(item any) {
this.locker.Lock()
_, ok := this.m[item]
if !ok {
// 是否已满
if len(this.keys) == this.maxSize {
var firstKey = this.keys[0]
this.keys = this.keys[1:]
delete(this.m, firstKey)
}
this.m[item] = zero.New()
this.keys = append(this.keys, item)
}
this.locker.Unlock()
}
func (this *FixedSet) Has(item any) bool {
this.locker.RLock()
defer this.locker.RUnlock()
_, ok := this.m[item]
return ok
}
func (this *FixedSet) Size() int {
this.locker.RLock()
defer this.locker.RUnlock()
return len(this.keys)
}
func (this *FixedSet) Reset() {
this.locker.Lock()
this.m = map[any]zero.Zero{}
this.keys = nil
this.locker.Unlock()
}

View File

@@ -0,0 +1,62 @@
// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
package setutils_test
import (
setutils "github.com/TeaOSLab/EdgeNode/internal/utils/sets"
"github.com/iwind/TeaGo/assert"
"github.com/iwind/TeaGo/rands"
"testing"
)
func TestNewFixedSet(t *testing.T) {
var a = assert.NewAssertion(t)
{
var set = setutils.NewFixedSet(0)
set.Push(1)
set.Push(2)
set.Push(2)
a.IsTrue(set.Size() == 2)
a.IsTrue(set.Has(1))
a.IsTrue(set.Has(2))
}
{
var set = setutils.NewFixedSet(1)
set.Push(1)
set.Push(2)
set.Push(3)
a.IsTrue(set.Size() == 1)
a.IsFalse(set.Has(1))
a.IsTrue(set.Has(3))
a.IsFalse(set.Has(4))
}
}
func TestFixedSet_Reset(t *testing.T) {
var a = assert.NewAssertion(t)
var set = setutils.NewFixedSet(3)
set.Push(1)
set.Push(2)
set.Push(3)
set.Reset()
a.IsTrue(set.Size() == 0)
}
func BenchmarkFixedSet_Has(b *testing.B) {
var count = 1_000_000
var set = setutils.NewFixedSet(count)
for i := 0; i < count; i++ {
set.Push(i)
}
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
set.Has(rands.Int(0, 100_000))
}
})
}