github.com/maynardminer/ethereumprogpow@v1.8.23/swarm/shed/field_struct.go (about)

     1  // Copyright 2018 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package shed
    18  
    19  import (
    20  	"github.com/ethereumprogpow/ethereumprogpow/rlp"
    21  	"github.com/syndtr/goleveldb/leveldb"
    22  )
    23  
    24  // StructField is a helper to store complex structure by
    25  // encoding it in RLP format.
    26  type StructField struct {
    27  	db  *DB
    28  	key []byte
    29  }
    30  
    31  // NewStructField returns a new StructField.
    32  // It validates its name and type against the database schema.
    33  func (db *DB) NewStructField(name string) (f StructField, err error) {
    34  	key, err := db.schemaFieldKey(name, "struct-rlp")
    35  	if err != nil {
    36  		return f, err
    37  	}
    38  	return StructField{
    39  		db:  db,
    40  		key: key,
    41  	}, nil
    42  }
    43  
    44  // Get unmarshals data from the database to a provided val.
    45  // If the data is not found leveldb.ErrNotFound is returned.
    46  func (f StructField) Get(val interface{}) (err error) {
    47  	b, err := f.db.Get(f.key)
    48  	if err != nil {
    49  		return err
    50  	}
    51  	return rlp.DecodeBytes(b, val)
    52  }
    53  
    54  // Put marshals provided val and saves it to the database.
    55  func (f StructField) Put(val interface{}) (err error) {
    56  	b, err := rlp.EncodeToBytes(val)
    57  	if err != nil {
    58  		return err
    59  	}
    60  	return f.db.Put(f.key, b)
    61  }
    62  
    63  // PutInBatch marshals provided val and puts it into the batch.
    64  func (f StructField) PutInBatch(batch *leveldb.Batch, val interface{}) (err error) {
    65  	b, err := rlp.EncodeToBytes(val)
    66  	if err != nil {
    67  		return err
    68  	}
    69  	batch.Put(f.key, b)
    70  	return nil
    71  }