diskvd

package module
v0.0.0-...-a8a2fee Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 23, 2024 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package diskvd provides a Diskv driver for go-shelve.

Example
package main

import (
	"fmt"
	"os"
	"path/filepath"

	diskvd "github.com/lucmq/go-shelve/driver/db/diskv"
	"github.com/lucmq/go-shelve/shelve"
)

var StoragePath = filepath.Join(os.TempDir(), "game-test", "db")

type Player struct {
	Name  string
	Level int
	Gold  int
	Items []string
}

type Config struct {
	Difficulty string
}

// NewShelf creates a customized Shelf using Diskv and JSON.
func NewShelf[V any](path string) (*shelve.Shelf[string, V], error) {
	path = filepath.Join(StoragePath, path)
	extension := "json" // Extension of the record files

	db, err := diskvd.NewDefault(path, extension)
	if err != nil {
		return nil, err
	}

	return shelve.Open[string, V](
		path,
		shelve.WithDatabase(db),
		shelve.WithCodec(shelve.JSONCodec()),
	)
}

func main() {
	// Open the shelf with custom options
	players, _ := NewShelf[Player]("players")
	config, _ := NewShelf[Config]("config")

	defer players.Close()
	defer config.Close()

	// Create the game data
	player := Player{
		Name:  "Frodo",
		Level: 14,
		Gold:  9999,
		Items: []string{"Sting", "Lembas"},
	}
	cfg := Config{
		Difficulty: "Hard",
	}

	// Save the data. Serialization and persistence will be
	// handled automatically by the Shelf.
	players.Put(player.Name, player)
	config.Put("config", cfg)

	// The app storage will contain readable JSON files with
	// configuration and game state, that can be retrieved
	// back to a Go type:
	value, ok, _ := players.Get("Frodo")
	fmt.Println(ok, value.Name, value.Items)

}
Output:

true Frodo [Sting Lembas]

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// DefaultCacheSize is the default size of the cache used when a Store is
	// created with NewDefault.
	DefaultCacheSize uint64 = 1024 * 1024

	// DefaultAdvancedTransform is the default function used to transform keys
	// to filesystem paths when a Store is created with NewDefault.
	DefaultAdvancedTransform = FilepathToPathKey

	// DefaultInverseTransform is the default function used map filesystem
	// paths back to keys when a Store is created with NewDefault. It is the
	// inverse of DefaultAdvancedTransform.
	DefaultInverseTransform = PathKeyToFilepath

	// DefaultLessFunction is the default function used to compare keys when a
	// Store is created with NewDefault.
	DefaultLessFunction = StringLess

	// DefaultBTreeDegree is the degree of the BTree used as the diskv index
	// when a Store is created with NewDefault.
	DefaultBTreeDegree = 8
)

Functions

func FilepathToPathKey

func FilepathToPathKey(path string) *diskv.PathKey

FilepathToPathKey converts a filepath to a PathKey. using the SplitFilepath function.

func PathKeyToFilepath

func PathKeyToFilepath(pk *diskv.PathKey) string

PathKeyToFilepath converts a diskv.PathKey to a filepath. It is the inverse of FilepathToPathKey.

func SplitFilepath

func SplitFilepath(path string) []string

SplitFilepath splits a path into its components. Examples:

  • "/a/b/c" -> ["a", "b", "c"]
  • "a/b/c" -> ["a", "b", "c"]
  • "a/b/c/" -> ["a", "b", "c"]
  • "a/b/c.txt" -> ["a", "b", "c.txt"]

func StringLess

func StringLess(a, b string) bool

StringLess returns true if a is less than b lexicographically.

Types

type IndexLen

type IndexLen interface {
	// Len returns the number of items in the index.
	Len() int
}

IndexLen is an interface that implementations of diskv.Index can use to make the Store.Len's method a no-op. By default, an instance of diskv.BTreeIndex is used, and it is not necessary to implement this interface.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store is a shelve.DB driver backed by a diskv.Diskv instance.

func New

func New(db *diskv.Diskv) (*Store, error)

New creates a new Store with the given diskv.Diskv instance.

func NewDefault

func NewDefault(path, extension string) (*Store, error)

NewDefault creates a new Store rooted at path with sensible default values. If extension is not empty, it will be appended to the path of each db record file.

func (*Store) Close

func (*Store) Close() error

Close closes the underlying diskv.Diskv instance. In diskv, this is a no-op.

func (*Store) Delete

func (s *Store) Delete(key []byte) error

Delete removes a key-value pair from the store.

func (*Store) Get

func (s *Store) Get(key []byte) ([]byte, error)

Get retrieves the value associated with a key from the store. If the key is not found, it returns nil.

func (*Store) Has

func (s *Store) Has(key []byte) (bool, error)

Has reports whether a key exists in the store.

func (*Store) Items

func (s *Store) Items(
	start []byte,
	_ int,
	fn func(key, value []byte) (bool, error),
) error

Items iterates over key-value pairs in the database, calling fn(k, v) for each pair in the sequence. The iteration stops early if the function fn returns false.

The start parameter specifies the key from which the iteration should start. If the start parameter is nil, the iteration will begin from the first key in the database.

The key-value pairs are returned in lexicographically sorted order but only forward iteration is supported. The order parameter exists only for compatibility with the shelve.DB interface and is ignored by this method.

func (*Store) Len

func (s *Store) Len() int64

Len returns the number of items in the store. It returns -1 if an error occurs.

Warning: Diskv doesn't provide a method to count the number of stored items and Len may iterate through the entire DB to retrieve this information.

If Diskv.Index is the default diskv.BTreeIndex, or satisfies the IndexLen interface from this package, this method is a no-op.

Otherwise, Len will default to iterating through the entire DB.

func (*Store) Put

func (s *Store) Put(key, value []byte) error

Put stores a key-value pair in the store. If the key already exists, it overwrites the existing value.

func (*Store) Sync

func (*Store) Sync() error

Sync synchronizes the underlying diskv database to persistent storage. In diskv, this is a no-op.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL