diff --git a/types/btccache.go b/types/btccache.go index d239ba3b..8023552a 100644 --- a/types/btccache.go +++ b/types/btccache.go @@ -32,7 +32,7 @@ func (b *BTCCache) Init(ibs []*IndexedBlock) error { return ErrTooManyEntries } for _, ib := range ibs { - if err := b.Add(ib); err != nil { + if err := b.add(ib); err != nil { return err } } @@ -40,11 +40,17 @@ func (b *BTCCache) Init(ibs []*IndexedBlock) error { return b.reverse() } +// Add adds a new block to the cache. Thread-safe. func (b *BTCCache) Add(ib *IndexedBlock) error { b.Lock() defer b.Unlock() - if b.Size() >= b.maxEntries { + return b.add(ib) +} + +// Thread-unsafe version of Add +func (b *BTCCache) add(ib *IndexedBlock) error { + if b.size() >= b.maxEntries { b.blocks = b.blocks[1:] } @@ -56,7 +62,7 @@ func (b *BTCCache) Tip() (*IndexedBlock, error) { b.RLock() defer b.RUnlock() - if b.Size() == 0 { + if b.size() == 0 { return nil, ErrEmptyCache } @@ -68,7 +74,7 @@ func (b *BTCCache) RemoveLast() error { b.Lock() defer b.Unlock() - if b.Size() == 0 { + if b.size() == 0 { return ErrEmptyCache } @@ -76,17 +82,29 @@ func (b *BTCCache) RemoveLast() error { return nil } +// Size returns the size of the cache. Thread-safe. func (b *BTCCache) Size() uint64 { b.RLock() defer b.RUnlock() + return b.size() +} + +// thread-unsafe version of Size +func (b *BTCCache) size() uint64 { return uint64(len(b.blocks)) } -func (b *BTCCache) reverse() error { +// Reverse reverses the order of blocks in cache in place. Thread-safe. +func (b *BTCCache) Reverse() error { b.Lock() defer b.Unlock() + return b.reverse() +} + +// thread-unsafe version of Reverse +func (b *BTCCache) reverse() error { for i, j := 0, len(b.blocks)-1; i < j; i, j = i+1, j-1 { b.blocks[i], b.blocks[j] = b.blocks[j], b.blocks[i] }