github.com/qri-io/qri@v0.10.1-0.20220104210721-c771715036cb/repo/mem_refstore.go (about)

     1  package repo
     2  
     3  import (
     4  	"sort"
     5  
     6  	reporef "github.com/qri-io/qri/repo/ref"
     7  )
     8  
     9  // MemRefstore is an in-memory implementation of the Namestore interface
    10  type MemRefstore []reporef.DatasetRef
    11  
    12  // PutRef adds a reference to the namestore. Only complete references may be added
    13  func (r *MemRefstore) PutRef(put reporef.DatasetRef) error {
    14  	if put.ProfileID == "" {
    15  		return ErrPeerIDRequired
    16  	} else if put.Peername == "" {
    17  		return ErrPeernameRequired
    18  	} else if put.Name == "" {
    19  		return ErrNameRequired
    20  	} else if put.Path == "" && put.FSIPath == "" {
    21  		return ErrPathRequired
    22  	}
    23  
    24  	for i, ref := range *r {
    25  		if ref.Match(put) {
    26  			rs := *r
    27  			rs[i] = put
    28  			return nil
    29  		}
    30  	}
    31  	*r = append(*r, put)
    32  	sl := *r
    33  	sort.Slice(sl, func(i, j int) bool { return sl[i].Peername+sl[i].Name < sl[j].Peername+sl[j].Name })
    34  	*r = sl
    35  	return nil
    36  }
    37  
    38  // GetRef completes a reference with , refs can have either
    39  // Path or Peername & Name specified, GetRef should fill out the missing pieces
    40  func (r MemRefstore) GetRef(get reporef.DatasetRef) (ref reporef.DatasetRef, err error) {
    41  	for _, ref := range r {
    42  		if ref.Match(get) {
    43  			return ref, nil
    44  		}
    45  	}
    46  	err = ErrNotFound
    47  	return
    48  }
    49  
    50  // DeleteRef removes a name from the store
    51  func (r *MemRefstore) DeleteRef(del reporef.DatasetRef) error {
    52  	refs := *r
    53  	for i, ref := range refs {
    54  		if ref.Match(del) {
    55  			*r = append(refs[:i], refs[i+1:]...)
    56  			return nil
    57  		}
    58  	}
    59  	return ErrNotFound
    60  }
    61  
    62  // References grabs a set of names from the Store's namespace
    63  func (r MemRefstore) References(offset, limit int) ([]reporef.DatasetRef, error) {
    64  	res := make([]reporef.DatasetRef, limit)
    65  	for i, ref := range r {
    66  		if i < offset {
    67  			continue
    68  		}
    69  		if i-offset == limit {
    70  			return res, nil
    71  		}
    72  		res[i-offset] = ref
    73  	}
    74  	return res[:len(r)-offset], nil
    75  }
    76  
    77  // RefCount returns the total number of names in the store
    78  func (r MemRefstore) RefCount() (int, error) {
    79  	return len(r), nil
    80  }