-
Notifications
You must be signed in to change notification settings - Fork 338
/
inmemchunkstore.go
87 lines (67 loc) · 1.63 KB
/
inmemchunkstore.go
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// Copyright 2022 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package inmemchunkstore
import (
"context"
"sync"
storage "github.com/ethersphere/bee/pkg/storage"
"github.com/ethersphere/bee/pkg/swarm"
)
type ChunkStore struct {
mu sync.Mutex
chunks map[string]swarm.Chunk
}
func New() *ChunkStore {
return &ChunkStore{
chunks: make(map[string]swarm.Chunk),
}
}
func (c *ChunkStore) Get(_ context.Context, addr swarm.Address) (swarm.Chunk, error) {
c.mu.Lock()
defer c.mu.Unlock()
chunk, ok := c.chunks[addr.ByteString()]
if !ok {
return nil, storage.ErrNotFound
}
return chunk, nil
}
func (c *ChunkStore) Put(_ context.Context, ch swarm.Chunk) error {
c.mu.Lock()
defer c.mu.Unlock()
chunk, ok := c.chunks[ch.Address().ByteString()]
if !ok {
chunk = swarm.NewChunk(ch.Address(), ch.Data()).WithStamp(ch.Stamp())
}
c.chunks[ch.Address().ByteString()] = chunk
return nil
}
func (c *ChunkStore) Has(_ context.Context, addr swarm.Address) (bool, error) {
c.mu.Lock()
defer c.mu.Unlock()
_, exists := c.chunks[addr.ByteString()]
return exists, nil
}
func (c *ChunkStore) Delete(_ context.Context, addr swarm.Address) error {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.chunks, addr.ByteString())
return nil
}
func (c *ChunkStore) Iterate(_ context.Context, fn storage.IterateChunkFn) error {
c.mu.Lock()
defer c.mu.Unlock()
for _, chunk := range c.chunks {
stop, err := fn(chunk)
if err != nil {
return err
}
if stop {
return nil
}
}
return nil
}
func (c *ChunkStore) Close() error {
return nil
}