mem.go (2308B)
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 dumpIdx int 22 dumpKeys []string 23 } 24 25 // NewmemDb returns an in-process volatile Db implementation. 26 func NewMemDb() *memDb { 27 db := &memDb{ 28 DbBase: db.NewDbBase(), 29 dumpIdx: -1, 30 } 31 return db 32 } 33 34 // Base implements Db 35 func (mdb *memDb) Base() *db.DbBase { 36 return mdb.DbBase 37 } 38 39 // String implements the string interface. 40 func (mdb *memDb) String() string { 41 return "memdb" 42 } 43 44 // Connect implements Db 45 func (mdb *memDb) Connect(ctx context.Context, connStr string) error { 46 if mdb.store != nil { 47 logg.WarnCtxf(ctx, "already connected") 48 return nil 49 } 50 mdb.store = make(map[string][]byte) 51 return nil 52 } 53 54 // convert to a supported map key type 55 func (mdb *memDb) toHexKey(ctx context.Context, key []byte) (memLookupKey, error) { 56 var mk memLookupKey 57 lk, err := mdb.ToKey(ctx, key) 58 mk.Default = hex.EncodeToString(lk.Default) 59 if lk.Translation != nil { 60 mk.Translation = hex.EncodeToString(lk.Translation) 61 } 62 logg.TraceCtxf(ctx, "converted key", "orig", key, "b", lk, "s", mk) 63 return mk, err 64 } 65 66 // Get implements Db 67 func (mdb *memDb) Get(ctx context.Context, key []byte) ([]byte, error) { 68 var v []byte 69 var ok bool 70 mk, err := mdb.toHexKey(ctx, key) 71 if err != nil { 72 return nil, err 73 } 74 logg.TraceCtxf(ctx, "mem get", "k", mk) 75 if mk.Translation != "" { 76 v, ok = mdb.store[mk.Translation] 77 if ok { 78 return v, nil 79 } 80 } 81 v, ok = mdb.store[mk.Default] 82 if !ok { 83 //b, _ := hex.DecodeString(k) 84 return nil, db.NewErrNotFound(key) 85 } 86 return v, nil 87 } 88 89 // Put implements Db 90 func (mdb *memDb) Put(ctx context.Context, key []byte, val []byte) error { 91 var k string 92 if !mdb.CheckPut() { 93 return errors.New("unsafe put and safety set") 94 } 95 mk, err := mdb.toHexKey(ctx, key) 96 if err != nil { 97 return err 98 } 99 if mk.Translation != "" { 100 k = mk.Translation 101 } else { 102 k = mk.Default 103 } 104 mdb.store[k] = val 105 logg.TraceCtxf(ctx, "mem put", "k", k, "mk", mk, "v", val) 106 return nil 107 } 108 109 // Close implements Db 110 func (mdb *memDb) Close(ctx context.Context) error { 111 return nil 112 }