github.com/ethersphere/bee/v2@v2.2.0/pkg/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  	"encoding/json"
    21  	"fmt"
    22  
    23  	"github.com/syndtr/goleveldb/leveldb"
    24  )
    25  
    26  // StructField is a helper to store complex structure by
    27  // encoding it in RLP format.
    28  type StructField struct {
    29  	db  *DB
    30  	key []byte
    31  }
    32  
    33  // NewStructField returns a new StructField.
    34  // It validates its name and type against the database schema.
    35  func (db *DB) NewStructField(name string) (f StructField, err error) {
    36  	key, err := db.schemaFieldKey(name, "struct-rlp")
    37  	if err != nil {
    38  		return f, fmt.Errorf("get schema key: %w", err)
    39  	}
    40  	return StructField{
    41  		db:  db,
    42  		key: key,
    43  	}, nil
    44  }
    45  
    46  // Get unmarshals data from the database to a provided val.
    47  // If the data is not found leveldb.ErrNotFound is returned.
    48  func (f StructField) Get(val interface{}) (err error) {
    49  	b, err := f.db.Get(f.key)
    50  	if err != nil {
    51  		return err
    52  	}
    53  	return json.Unmarshal(b, val)
    54  }
    55  
    56  // Put marshals provided val and saves it to the database.
    57  func (f StructField) Put(val interface{}) (err error) {
    58  	b, err := json.Marshal(val)
    59  	if err != nil {
    60  		return err
    61  	}
    62  	return f.db.Put(f.key, b)
    63  }
    64  
    65  // PutInBatch marshals provided val and puts it into the batch.
    66  func (f StructField) PutInBatch(batch *leveldb.Batch, val interface{}) (err error) {
    67  	b, err := json.Marshal(val)
    68  	if err != nil {
    69  		return err
    70  	}
    71  	batch.Put(f.key, b)
    72  	return nil
    73  }