-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemorystorage.go
More file actions
67 lines (53 loc) · 1.43 KB
/
memorystorage.go
File metadata and controls
67 lines (53 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package sebtopic
import (
"bytes"
"fmt"
"io"
"strings"
"sync"
"github.com/micvbang/simple-event-broker/internal/infrastructure/logger"
"github.com/micvbang/simple-event-broker/internal/infrastructure/nops"
"github.com/micvbang/simple-event-broker/seberr"
)
// MemoryTopicStorage is an in-memory backing storage that can be used in Topic.
// It is mostly useful for testing.
type MemoryTopicStorage struct {
mu sync.Mutex
storage map[string]*bytes.Buffer
}
func NewMemoryStorage(log logger.Logger) *MemoryTopicStorage {
return &MemoryTopicStorage{
storage: make(map[string]*bytes.Buffer, 64),
}
}
func (ms *MemoryTopicStorage) Writer(key string) (io.WriteCloser, error) {
ms.mu.Lock()
defer ms.mu.Unlock()
buf := bytes.NewBuffer(make([]byte, 0, 4096))
ms.storage[key] = buf
return nops.NopWriteCloser(buf), nil
}
func (ms *MemoryTopicStorage) Reader(key string) (io.ReadCloser, error) {
ms.mu.Lock()
defer ms.mu.Unlock()
buf, ok := ms.storage[key]
if !ok {
return nil, seberr.ErrNotInStorage
}
return io.NopCloser(buf), nil
}
func (ms *MemoryTopicStorage) ListFiles(topicName string, extension string) ([]File, error) {
ms.mu.Lock()
defer ms.mu.Unlock()
files := make([]File, 0, 128)
topicPrefix := fmt.Sprintf("%s/", topicName)
for key, buf := range ms.storage {
if strings.HasPrefix(key, topicPrefix) {
files = append(files, File{
Size: int64(buf.Len()),
Path: key,
})
}
}
return files, nil
}