mem.go (2150B)
1 package mem 2 3 import ( 4 "context" 5 "encoding/hex" 6 "errors" 7 8 "git.defalsify.org/vise.git/db" 9 ) 10 11 // holds string (hex) versions of lookupKey 12 type memLookupKey struct { 13 Default string 14 Translation string 15 } 16 17 // memDb is a memory backend implementation of the Db interface. 18 type memDb struct { 19 *db.DbBase 20 store map[string][]byte 21 } 22 23 // NewmemDb returns an in-process volatile Db implementation. 24 func NewMemDb() *memDb { 25 db := &memDb{ 26 DbBase: db.NewDbBase(), 27 } 28 return db 29 } 30 31 // String implements the string interface. 32 func(mdb *memDb) String() string { 33 return "memdb" 34 } 35 36 // Connect implements Db 37 func(mdb *memDb) Connect(ctx context.Context, connStr string) error { 38 if mdb.store != nil { 39 logg.WarnCtxf(ctx, "already connected") 40 return nil 41 } 42 mdb.store = make(map[string][]byte) 43 return nil 44 } 45 46 // convert to a supported map key type 47 func(mdb *memDb) toHexKey(ctx context.Context, key []byte) (memLookupKey, error) { 48 var mk memLookupKey 49 lk, err := mdb.ToKey(ctx, key) 50 mk.Default = hex.EncodeToString(lk.Default) 51 if lk.Translation != nil { 52 mk.Translation = hex.EncodeToString(lk.Translation) 53 } 54 logg.TraceCtxf(ctx, "converted key", "orig", key, "b", lk, "s", mk) 55 return mk, err 56 } 57 58 // Get implements Db 59 func(mdb *memDb) Get(ctx context.Context, key []byte) ([]byte, error) { 60 var v []byte 61 var ok bool 62 mk, err := mdb.toHexKey(ctx, key) 63 if err != nil { 64 return nil, err 65 } 66 logg.TraceCtxf(ctx, "mem get", "k", mk) 67 if mk.Translation != "" { 68 v, ok = mdb.store[mk.Translation] 69 if ok { 70 return v, nil 71 } 72 } 73 v, ok = mdb.store[mk.Default] 74 if !ok { 75 //b, _ := hex.DecodeString(k) 76 return nil, db.NewErrNotFound(key) 77 } 78 return v, nil 79 } 80 81 // Put implements Db 82 func(mdb *memDb) Put(ctx context.Context, key []byte, val []byte) error { 83 var k string 84 if !mdb.CheckPut() { 85 return errors.New("unsafe put and safety set") 86 } 87 mk, err := mdb.toHexKey(ctx, key) 88 if err != nil { 89 return err 90 } 91 if mk.Translation != "" { 92 k = mk.Translation 93 } else { 94 k = mk.Default 95 } 96 mdb.store[k] = val 97 logg.TraceCtxf(ctx, "mem put", "k", k, "mk", mk, "v", val) 98 return nil 99 } 100 101 // Close implements Db 102 func(mdb *memDb) Close() error { 103 return nil 104 }