github.com/safing/portbase@v0.19.5/runtime/singe_record_provider.go (about)

     1  package runtime
     2  
     3  import "github.com/safing/portbase/database/record"
     4  
     5  // singleRecordReader is a convenience type for read-only exposing
     6  // a single record.Record. Note that users must lock the whole record
     7  // themself before performing any manipulation on the record.
     8  type singleRecordReader struct {
     9  	record.Record
    10  }
    11  
    12  // ProvideRecord returns a ValueProvider the exposes read-only
    13  // access to r. Users of ProvideRecord need to ensure the lock
    14  // the whole record before performing modifications on it.
    15  //
    16  // Example:
    17  //
    18  //	type MyValue struct {
    19  //		record.Base
    20  //		Value string
    21  //	}
    22  //	r := new(MyValue)
    23  //	pushUpdate, _ := runtime.Register("my/key", ProvideRecord(r))
    24  //	r.Lock()
    25  //	r.Value = "foobar"
    26  //	pushUpdate(r)
    27  //	r.Unlock()
    28  func ProvideRecord(r record.Record) ValueProvider {
    29  	return &singleRecordReader{r}
    30  }
    31  
    32  // Set implements ValueProvider.Set and returns ErrReadOnly.
    33  func (sr *singleRecordReader) Set(_ record.Record) (record.Record, error) {
    34  	return nil, ErrReadOnly
    35  }
    36  
    37  // Get implements ValueProvider.Get and returns the wrapped record.Record
    38  // but only if keyOrPrefix exactly matches the records database key.
    39  func (sr *singleRecordReader) Get(keyOrPrefix string) ([]record.Record, error) {
    40  	if keyOrPrefix != sr.Record.DatabaseKey() {
    41  		return nil, nil
    42  	}
    43  	return []record.Record{sr.Record}, nil
    44  }