type components struct {
MatchF func(mkey, key string) bool
- m []*CItem
- mm map[string]int
+ withLock bool
+ m []*CItem
+ mm map[string]int
sync.RWMutex
}
// strings.HasSuffix
//
// DotMatch
-func NewComp(matchf func(mkey, key string) bool) *components {
+func NewComp(withLock bool, matchf func(mkey, key string) bool) *components {
return &components{
- MatchF: matchf,
- mm: make(map[string]int),
+ MatchF: matchf,
+ withLock: withLock,
+ mm: make(map[string]int),
}
}
func (t *components) Put(item *CItem) error {
- t.Lock()
- defer t.Unlock()
+ if t.withLock {
+ t.Lock()
+ defer t.Unlock()
+ }
if _, ok := t.mm[item.Key]; ok {
return errors.Join(ErrConflict, errors.New(item.Key))
}
}
func (t *components) Del(key string) {
- t.Lock()
+ if t.withLock {
+ t.Lock()
+ defer t.Unlock()
+ }
for i := 0; i < len(t.m); i++ {
if t.MatchF(t.m[i].Key, key) {
delete(t.mm, t.m[i].Key)
for i := 0; i < len(t.m); i++ {
t.mm[t.m[i].Key] = i
}
- t.Unlock()
}
func (t *components) Run(key string, ctx context.Context, ptr any) error {
- t.RLock()
- defer t.RUnlock()
+ if t.withLock {
+ t.RLock()
+ defer t.RUnlock()
+ }
var (
i = 0
return errors.Join(ErrCItemErr, e)
}
}
+
if !got {
return errors.Join(ErrNotExist, errors.New(key))
}
return Comp.Run(key, ctx, ptr)
}
-func Init(f func(mkey, key string) bool) {
- Comp = NewComp(f)
+func Init(withLock bool, f func(mkey, key string) bool) {
+ Comp = NewComp(withLock, f)
}
func DotMatch(mkey, key string) bool {
return mkey == key || (len(mkey) > len(key) && mkey[0:len(key)] == key && mkey[len(key)] == '.')
}
-var Comp *components = NewComp(DotMatch)
+var Comp *components = NewComp(false, DotMatch)
)
func Test1(t *testing.T) {
- Init(DotMatch)
+ Init(false, DotMatch)
Put(`1`, func(ctx context.Context, ptr *int) error {
if *ptr > 1 {
}
func TestDot(t *testing.T) {
- Init(DotMatch)
+ Init(false, DotMatch)
Put[int](`1`, func(ctx context.Context, ptr *int) error {
if *ptr == 1 {
return nil
}
func Test3(t *testing.T) {
- Init(DotMatch)
+ Init(false, DotMatch)
sumup := func(ctx context.Context, ptr *int) error {
return nil
}
}
func Benchmark2(b *testing.B) {
- Init(DotMatch)
+ Init(false, DotMatch)
b.ResetTimer()
for i := 0; i < b.N; i++ {
Put[int](strconv.Itoa(i), func(ctx context.Context, ptr *int) error {
}
func Benchmark1(b *testing.B) {
- Init(DotMatch)
+ Init(false, DotMatch)
for i := 0; i < 1000; i++ {
- Put[int](strconv.Itoa(i), func(ctx context.Context, ptr *int) error {
+ Put[int](`1`, func(ctx context.Context, ptr *int) error {
return nil
})
}