storage.gno
1.30 Kb ยท 56 lines
1package simple
2
3import (
4 "time"
5
6 "gno.land/p/demo/gnorkle/feed"
7 "gno.land/p/demo/gnorkle/storage"
8)
9
10// Storage is simple, bounded storage for published feed values.
11type Storage struct {
12 values []feed.Value
13 maxValues uint
14}
15
16// NewStorage creates a new Storage with the given maximum number of values.
17// If maxValues is 0, the storage is bounded to a size of one. If this is not desirable,
18// then don't provide a value of 0.
19func NewStorage(maxValues uint) *Storage {
20 if maxValues == 0 {
21 maxValues = 1
22 }
23
24 return &Storage{
25 maxValues: maxValues,
26 }
27}
28
29// Put adds a new value to the storage. If the storage is full, the oldest value
30// is removed. If maxValues is 0, the storage is bounded to a size of one.
31func (s *Storage) Put(value string) error {
32 if s == nil {
33 return storage.ErrUndefined
34 }
35
36 s.values = append(s.values, feed.Value{String: value, Time: time.Now()})
37 if uint(len(s.values)) > s.maxValues {
38 s.values = s.values[1:]
39 }
40
41 return nil
42}
43
44// GetLatest returns the most recently added value, or an empty value if none exist.
45func (s Storage) GetLatest() feed.Value {
46 if len(s.values) == 0 {
47 return feed.Value{}
48 }
49
50 return s.values[len(s.values)-1]
51}
52
53// GetHistory returns all values in the storage, from oldest to newest.
54func (s Storage) GetHistory() []feed.Value {
55 return s.values
56}