github.com/filecoin-project/specs-actors/v4@v4.0.2/actors/migration/nv12/util.go (about)

     1  package nv12
     2  
     3  import (
     4  	"sync"
     5  	"testing"
     6  
     7  	"github.com/filecoin-project/go-state-types/rt"
     8  	"github.com/ipfs/go-cid"
     9  	"golang.org/x/xerrors"
    10  )
    11  
    12  type MemMigrationCache struct {
    13  	MigrationMap sync.Map
    14  }
    15  
    16  func NewMemMigrationCache() *MemMigrationCache {
    17  	return new(MemMigrationCache)
    18  }
    19  
    20  func (m *MemMigrationCache) Write(key string, c cid.Cid) error {
    21  	m.MigrationMap.Store(key, c)
    22  	return nil
    23  }
    24  
    25  func (m *MemMigrationCache) Read(key string) (bool, cid.Cid, error) {
    26  	val, found := m.MigrationMap.Load(key)
    27  	if !found {
    28  		return false, cid.Undef, nil
    29  	}
    30  	c, ok := val.(cid.Cid)
    31  	if !ok {
    32  		return false, cid.Undef, xerrors.Errorf("non cid value in cache")
    33  	}
    34  
    35  	return true, c, nil
    36  }
    37  
    38  func (m *MemMigrationCache) Load(key string, loadFunc func() (cid.Cid, error)) (cid.Cid, error) {
    39  	found, c, err := m.Read(key)
    40  	if err != nil {
    41  		return cid.Undef, err
    42  	}
    43  	if found {
    44  		return c, nil
    45  	}
    46  	c, err = loadFunc()
    47  	if err != nil {
    48  		return cid.Undef, err
    49  	}
    50  	m.MigrationMap.Store(key, c)
    51  	return c, nil
    52  }
    53  
    54  func (m *MemMigrationCache) Clone() *MemMigrationCache {
    55  	newCache := NewMemMigrationCache()
    56  	newCache.Update(m)
    57  	return newCache
    58  }
    59  
    60  func (m *MemMigrationCache) Update(other *MemMigrationCache) {
    61  	other.MigrationMap.Range(func(key, value interface{}) bool {
    62  		m.MigrationMap.Store(key, value)
    63  		return true
    64  	})
    65  }
    66  
    67  type TestLogger struct {
    68  	TB testing.TB
    69  }
    70  
    71  func (t TestLogger) Log(_ rt.LogLevel, msg string, args ...interface{}) {
    72  	t.TB.Logf(msg, args...)
    73  }