diff --git a/boltease.go b/boltease.go index 3af0af9..472ae04 100644 --- a/boltease.go +++ b/boltease.go @@ -37,7 +37,7 @@ func Create(fn string, m os.FileMode, opts *bolt.Options) (*DB, error) { // SetStruct takes a database, a path, a struct, and a function that takes a // path and an element and processes it. -func SetStruct[T any](b *DB, path []string, value T, fn func([]string, T) error) error { +func SetStructInDB[T any](b *DB, path []string, value T, fn func([]string, T) error) error { var err error if !b.dbIsOpen { if err = b.OpenDB(); err != nil { @@ -69,7 +69,7 @@ func SetStruct[T any](b *DB, path []string, value T, fn func([]string, T) error) // SetStructList takes a path, a slice of structs, and a function that takes // a bolt bucket and one element of the slice and processes it. -func SetStructList[T any](b *DB, path []string, values []T, fn func(*bolt.Bucket, T) error) error { +func SetStructListDB[T any](b *DB, path []string, values []T, fn func(*bolt.Bucket, T) error) error { var err error if !b.dbIsOpen { if err = b.OpenDB(); err != nil { diff --git a/bucket_funcs.go b/bucket_funcs.go index 8b1a3d9..157ab57 100644 --- a/bucket_funcs.go +++ b/bucket_funcs.go @@ -143,11 +143,12 @@ func GetBool(bkt *bolt.Bucket, key string) (bool, error) { if err != nil { return false, err } - if r == "true" || r == "1" { + switch r { + case "true", "1": return true, nil - } else if r == "false" || r == "0" { + case "false", "0": return false, nil - } else { + default: return false, fmt.Errorf("cannot parse as a boolean") } } @@ -384,3 +385,53 @@ func SetKeyValueStringMap(bkt *bolt.Bucket, kvMap map[string]string) error { } return SetKeyValueMap(bkt, chain) } + +func GetStruct[T any](bkt *bolt.Bucket, fn func(*bolt.Bucket) (T, error)) (T, error) { + return fn(bkt) +} + +func SetStruct[T any](bkt *bolt.Bucket, value T, fn func(*bolt.Bucket, T) error) error { + return fn(bkt, value) +} + +func GetStructList[T any](bkt *bolt.Bucket, fn func(*bolt.Bucket) (T, error)) ([]T, error) { + var ret []T + if bkt == nil { + return nil, fmt.Errorf("bucket must not be nil") + } + keyList, err := GetBucketList(bkt) + if err != nil { + return nil, err + } + for _, k := range keyList { + sBkt, err := GetBucket(bkt, k) + if err != nil { + return nil, err + } + v, err := fn(sBkt) + if err != nil { + return nil, err + } + ret = append(ret, v) + } + return ret, nil +} + +func SetStructList[T any](bkt *bolt.Bucket, values []T, fn func(*bolt.Bucket, T) error) error { + bkt.SetSequence(0) + for _, v := range values { + id, _ := bkt.NextSequence() + bId := make([]byte, 8) + binary.BigEndian.PutUint64(bId, id) + // Delete the bucket if it already exists + bkt.DeleteBucket(bId) + structBkt, err := bkt.CreateBucketIfNotExists(bId) + if err != nil { + return err + } + if err = fn(structBkt, v); err != nil { + return err + } + } + return nil +}