Fix saving pointer values to memory keyvalue

This commit is contained in:
kolaente 2021-05-31 20:54:15 +02:00
parent d48aa101cf
commit 9a2655dbf1
No known key found for this signature in database
GPG key ID: F40E70337AB24C9B

View file

@ -17,10 +17,9 @@
package memory package memory
import ( import (
e "code.vikunja.io/api/pkg/modules/keyvalue/error"
"reflect" "reflect"
"sync" "sync"
e "code.vikunja.io/api/pkg/modules/keyvalue/error"
) )
// Storage is the memory implementation of a storage backend // Storage is the memory implementation of a storage backend
@ -40,6 +39,14 @@ func NewStorage() *Storage {
func (s *Storage) Put(key string, value interface{}) (err error) { func (s *Storage) Put(key string, value interface{}) (err error) {
s.mutex.Lock() s.mutex.Lock()
defer s.mutex.Unlock() defer s.mutex.Unlock()
val := reflect.ValueOf(value)
// Make sure to store the underlying value when value is a pointer to a value
if val.Kind() == reflect.Ptr {
s.store[key] = val.Elem().Interface()
return nil
}
s.store[key] = value s.store[key] = value
return nil return nil
} }
@ -53,18 +60,22 @@ func (s *Storage) Get(key string) (value interface{}, exists bool, err error) {
return return
} }
func (s *Storage) GetWithValue(key string, value interface{}) (exists bool, err error) { func (s *Storage) GetWithValue(key string, ptr interface{}) (exists bool, err error) {
v, exists, err := s.Get(key) stored, exists, err := s.Get(key)
if !exists { if !exists {
return exists, err return exists, err
} }
val := reflect.ValueOf(value) val := reflect.ValueOf(ptr)
if val.Kind() != reflect.Ptr { if val.Kind() != reflect.Ptr {
panic("some: check must be a pointer") panic("value must be a pointer")
}
if val.IsNil() {
panic("pointer must not be a nil-pointer")
} }
val.Elem().Set(reflect.ValueOf(v)) val.Elem().Set(reflect.ValueOf(stored))
return exists, err return exists, err
} }