1 // Copyright 2019 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
14 // Mem is an in-memory implementation of Storage.
15 // It is meant for tests and does not store any data to persistent storage.
17 // The zero value is an empty Mem ready for use.
20 table map[string]string
23 // A memTx is a transaction in a Mem.
29 // errRetry is an internal sentinel indicating that the transaction should be retried.
30 // It is never returned to the caller.
31 var errRetry = errors.New("retry")
33 // ReadOnly runs f in a read-only transaction.
34 func (m *Mem) ReadOnly(ctx context.Context, f func(context.Context, Transaction) error) error {
41 if err := f(ctx, tx); err != nil {
44 // Spurious retry with 10% probability.
45 if rand.Intn(10) == 0 {
56 // ReadWrite runs f in a read-write transaction.
57 func (m *Mem) ReadWrite(ctx context.Context, f func(context.Context, Transaction) error) error {
65 if err := f(ctx, tx); err != nil {
68 // Spurious retry with 10% probability.
69 if rand.Intn(10) == 0 {
73 m.table = make(map[string]string)
75 for _, w := range tx.writes {
77 delete(m.table, w.Key)
79 m.table[w.Key] = w.Value
90 // ReadValues returns the values associated with the given keys.
91 func (tx *memTx) ReadValues(ctx context.Context, keys []string) ([]string, error) {
92 vals := make([]string, len(keys))
93 for i, key := range keys {
94 vals[i] = tx.m.table[key]
99 // ReadValue returns the value associated with the single key.
100 func (tx *memTx) ReadValue(ctx context.Context, key string) (string, error) {
101 return tx.m.table[key], nil
104 // BufferWrites buffers a list of writes to be applied
105 // to the table when the transaction commits.
106 // The changes are not visible to reads within the transaction.
107 // The map argument is not used after the call returns.
108 func (tx *memTx) BufferWrites(list []Write) error {
109 if tx.writes == nil {
110 panic("BufferWrite on read-only transaction")
112 tx.writes = append(tx.writes, list...)