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