You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

162 lines
2.9 KiB

// ------------------------------------------------------------------------
// 🚀 Project active3
// 🔗 Active Thing (activething.com) git.activething.com/go
//
// File name grepo.go
// ✍️ Created by DEV
// 📅 Modified 06/05/2024
//
// 🔒 Copyright 2024 activething.com
//
// 📜 LICENSE --------------------------------------------------------------
// 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 reps
import (
"sync"
"syns"
)
type (
GRepo [K comparable, V any] struct {
syns.LockerRW
items map[K]V
def V
validatorFn func(item V) bool
}
GRepoFnc[K comparable, V any] func (r *GRepo[K,V])
)
func NewGRepo [K comparable, V any](def V, safe bool, options ...GRepoFnc[K,V]) *GRepo[K,V] {
lk := syns.LockerRW (syns.NopLocker{})
if safe {
lk = &sync.RWMutex{}
}
rp := &GRepo[K,V]{
LockerRW : lk,
items : make(map[K]V),
validatorFn : func(_ V) bool { return true },
}
for _,o := range options {
o(rp)
}
return rp
}
func (r *GRepo[_,_]) Len () int {
r.RLock()
l := len(r.items)
r.RUnlock()
return l
}
func (r *GRepo[K, V]) Has (key K) bool {
r.RLock()
_,hs := r.items[key]
r.RUnlock()
return hs
}
func (r *GRepo[K, V]) Get (key K) (V,bool) {
r.RLock()
v,hs := r.items[key]
r.RUnlock()
return v,hs
}
func (r *GRepo[K, V]) GetOrDefault (key K) V {
r.RLock()
v,hs := r.items[key]
if !hs {
v = r.def
}
r.RUnlock()
return v
}
func (r *GRepo[K, V]) Reg (key K, item V) error {
r.Lock()
if r.validatorFn != nil && !r.validatorFn(item) {
r.Unlock()
return G.ErrInvalidItem
}
if _,hs := r.items[key]; hs {
r.Unlock()
return G.ErrDuplicatedItem
}
r.items[key]=item
r.Unlock()
return nil
}
func (r *GRepo[K, V]) Set (key K, item V) {
r.Lock()
if r.validatorFn != nil && !r.validatorFn(item) {
r.Unlock()
return
}
r.items[key]=item
r.Unlock()
}
func (r *GRepo[K, _]) Del (key ...K) {
r.Lock()
for _,k := range key {
delete(r.items, k)
}
r.Unlock()
}
func (r *GRepo[K,V]) GetAll (all bool, key...K) ([]V,int) {
c := 0
var l []V
for _,k := range key {
v,hs := r.items[k]
if hs {
l = append(l, v)
continue
}
if all {
return nil,-1
}
c-=1
}
return l,c
}
func RepoWithValidator[K comparable,T any] (validator func(item T) bool) GRepoFnc[K,T] {
return func(r *GRepo[K,T]) {
r.validatorFn = validator } }

Powered by TurnKey Linux.