github.com/ethersphere/bee/v2@v2.2.0/pkg/shed/field_string.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  	"errors"
    21  	"fmt"
    22  
    23  	"github.com/syndtr/goleveldb/leveldb"
    24  )
    25  
    26  // StringField is the most simple field implementation
    27  // that stores an arbitrary string under a specific LevelDB key.
    28  type StringField struct {
    29  	db  *DB
    30  	key []byte
    31  }
    32  
    33  // NewStringField returns a new Instance of StringField.
    34  // It validates its name and type against the database schema.
    35  func (db *DB) NewStringField(name string) (f StringField, err error) {
    36  	key, err := db.schemaFieldKey(name, "string")
    37  	if err != nil {
    38  		return f, fmt.Errorf("get schema key: %w", err)
    39  	}
    40  	return StringField{
    41  		db:  db,
    42  		key: key,
    43  	}, nil
    44  }
    45  
    46  // Get returns a string value from database.
    47  // If the value is not found, an empty string is returned
    48  // an no error.
    49  func (f StringField) Get() (val string, err error) {
    50  	b, err := f.db.Get(f.key)
    51  	if err != nil {
    52  		if errors.Is(err, leveldb.ErrNotFound) {
    53  			return "", nil
    54  		}
    55  		return "", err
    56  	}
    57  	return string(b), nil
    58  }
    59  
    60  // Put stores a string in the database.
    61  func (f StringField) Put(val string) (err error) {
    62  	return f.db.Put(f.key, []byte(val))
    63  }
    64  
    65  // PutInBatch stores a string in a batch that can be
    66  // saved later in database.
    67  func (f StringField) PutInBatch(batch *leveldb.Batch, val string) {
    68  	batch.Put(f.key, []byte(val))
    69  }