Справочник API собран из Go doc-комментариев в исходном коде и написан на английском языке.
package save
import "github.com/nsgo-dev/game/pkg/save"Обзор
Package save stores a game's save slots as versioned JSON in either the app's key-value storage (core.Storage) or files in a directory such as cx.DataDir.
Each slot holds a {"version": N, "data": ...} envelope; an envelope with any other field, or with a field given twice, is corrupt. When a Store loads a save written by an older version, it runs its registered migrations one version at a time (v to v+1) before unmarshaling into the caller's value; a save from a newer version is refused with ErrFutureVersion rather than read into an older shape.
Writes keep the previous valid save as a backup before replacing the primary copy (with a write, sync and rename on disk, or a backup key in core.Storage), so a failed write leaves the last good save intact and a corrupted primary falls back to the backup on Load.
Player settings (audio, bindings, display, locale, accessibility and custom preferences) are persisted separately via SettingsStore and DefaultSettingsStore outside the save-slot namespace, so deleting or clearing save slots never touches player settings, and LoadAndApply wires loaded settings to game subsystems on startup.
Указатель
- Переменные
- func Apply(s Settings, targets SettingsTargets) error
- func ValidateSlot(slot string) error
- type AccessibilitySettings
- type AudioSettings
- type Backend
- type DefaultSettingsStore
- func NewDefaultSettingsStore(backend Backend, opts ...SettingsOption) *DefaultSettingsStore
- func NewFileSettingsStore(dir string, opts ...SettingsOption) *DefaultSettingsStore
- func NewStorageSettingsStore(store core.Storage, prefix string, opts ...SettingsOption) *DefaultSettingsStore
- func (s *DefaultSettingsStore) LoadAndApply(targets SettingsTargets) (Settings, error)
- type DisplaySettings
- type Migration
- type Option
- type Settings
- type SettingsOption
- type SettingsSchema
- type SettingsStore
- func NewSettingsStore[T any](backend Backend, defaults func() T, opts ...SettingsOption) *SettingsStore[T]
- func (s *SettingsStore[T]) Delete() error
- func (s *SettingsStore[T]) Exists() bool
- func (s *SettingsStore[T]) Load() (T, error)
- func (s *SettingsStore[T]) RegisterMigration(from int, fn Migration)
- func (s *SettingsStore[T]) Reset() error
- func (s *SettingsStore[T]) Save(value T) error
- type SettingsTargets
- type Store
- func NewFileStore(dir string, opts ...Option) *Store
- func NewStorageStore(store core.Storage, prefix string, opts ...Option) *Store
- func NewStore(backend Backend, opts ...Option) *Store
- func (s *Store) Delete(slot string) error
- func (s *Store) DeleteAll() error
- func (s *Store) Exists(slot string) bool
- func (s *Store) Load(slot string, dst any) error
- func (s *Store) LoadChecked(slot string, dst any, check func() error) error
- func (s *Store) RegisterMigration(from int, fn Migration)
- func (s *Store) Save(slot string, value any) error
- func (s *Store) Slots() ([]string, error)
Переменные
var (
// ErrNotFound reports that no save exists in the named slot.
ErrNotFound = errors.New("save: slot not found")
// ErrInvalidSlot reports that a slot name is empty or unsafe for storage keys or file paths.
ErrInvalidSlot = errors.New("save: invalid slot name")
// ErrFutureVersion reports that a save was written by a newer schema version than the store supports.
ErrFutureVersion = errors.New("save: version newer than supported")
// ErrMissingMigration reports that a store lacks a migration step needed to bring a save up to its current version.
ErrMissingMigration = errors.New("save: missing migration")
// ErrCorrupt reports that a save's stored payload is not a valid save envelope.
ErrCorrupt = errors.New("save: corrupt data")
)Функции
func Apply(s Settings, targets SettingsTargets) errorApply validates a copy of s and dispatches its sections to every non-nil target in targets. All non-nil targets are invoked even if an earlier target returns an error; errors are combined with errors.Join.
func ValidateSlot(slot string) errorValidateSlot reports whether slot is a name a Store accepts, returning an error wrapping ErrInvalidSlot when it is not. Code that takes slot names from outside the game, such as a cloud listing, checks them with it before handing them to a Backend.
Типы
type AccessibilitySettings struct {
Captions bool `json:"captions"`
// CaptionScale is the subtitle/caption scale factor in [0.5, 3.0] (1.0 by default).
CaptionScale float64 `json:"caption_scale"`
ColorBlindMode string `json:"color_blind_mode,omitempty"`
ReduceMotion bool `json:"reduce_motion"`
HighContrast bool `json:"high_contrast"`
// ScreenShake is the camera shake intensity in [0, 1] (1.0 by default, 0 disables shake).
ScreenShake float64 `json:"screen_shake"`
// GameSpeed is the gameplay speed multiplier in [0.25, 2.0] (1.0 by default).
GameSpeed float64 `json:"game_speed"`
}AccessibilitySettings holds player accessibility preferences.
type AudioSettings struct {
// Master is the overall volume in [0, 1] (1.0 by default).
Master float64 `json:"master"`
// Groups maps audio group names (such as "music", "sfx", "ui") to volumes in [0, 1].
Groups map[string]float64 `json:"groups,omitempty"`
// Muted silences all audio without discarding the stored Master level.
Muted bool `json:"muted"`
}AudioSettings holds player audio preferences stored independently of save slots.
func (a *AudioSettings) UnmarshalJSON(data []byte) errorUnmarshalJSON decodes AudioSettings while preserving defaults for omitted fields and replacing Groups cleanly when "groups" is explicitly present in JSON.
type Backend interface {
// Read returns the primary payload for slot, or an error wrapping ErrNotFound if absent.
Read(slot string) ([]byte, error)
// ReadBackup returns the previous valid payload kept as a backup for slot, or an error wrapping ErrNotFound if absent.
ReadBackup(slot string) ([]byte, error)
// Write saves data as the primary payload for slot, preserving any existing valid primary as the backup first.
Write(slot string, data []byte) error
// Delete removes both primary and backup payloads for slot, the backup first so an interrupted Delete never leaves a backup that resurrects the slot. Deleting an absent slot returns nil.
Delete(slot string) error
// Exists reports whether a primary or backup payload exists for slot.
Exists(slot string) bool
// Slots returns the sorted names of all slots that have a primary or backup payload.
Slots() ([]string, error)
}Backend stores and retrieves raw save payloads and their backup copies by validated slot name.
A Backend that wraps another, such as one that records each write, can expose it with an Unwrap() Backend method. A SettingsStore built on the wrapper then keeps settings exactly where it would on the wrapped backend, without passing them through the wrapper.
func FileBackend(dir string) BackendFileBackend returns a Backend that keeps each slot as <slot>.json and its backup as <slot>.json.bak inside dir (such as cx.DataDir()).
Writes stage data into a synced temporary file in dir, preserve any existing valid primary in <slot>.json.bak, atomically rename the temporary file into place and sync the directory, reporting a failed directory sync as a write error. The first Write removes .save-*.tmp files that an interrupted write left more than an hour ago. On the web, where Scope.DataDir is empty, use StorageBackend instead.
func StorageBackend(store core.Storage, prefix string) BackendStorageBackend returns a Backend that keeps saves in store under keys starting with prefix.
Each slot uses a primary key (<prefix>.slot.<slot>) and a backup key (<prefix>.bak.<slot>), so backup keys never collide with slot names and a failed SetItem (such as *core.StorageFullError) leaves the previous save intact.
type DefaultSettingsStore struct {
*SettingsStore[Settings]
}DefaultSettingsStore is a convenience SettingsStore for the standard Settings struct with startup Apply support.
func NewDefaultSettingsStore(backend Backend, opts ...SettingsOption) *DefaultSettingsStoreNewDefaultSettingsStore returns a DefaultSettingsStore backed by backend.
func NewFileSettingsStore(dir string, opts ...SettingsOption) *DefaultSettingsStoreNewFileSettingsStore returns a DefaultSettingsStore backed by settings.json (and settings.json.bak) inside dir.
func NewStorageSettingsStore(store core.Storage, prefix string, opts ...SettingsOption) *DefaultSettingsStoreNewStorageSettingsStore returns a DefaultSettingsStore backed by store under <prefix>.settings (outside the slot namespace).
func (s *DefaultSettingsStore) LoadAndApply(targets SettingsTargets) (Settings, error)LoadAndApply loads settings (returning DefaultSettings when absent) and applies them to targets. If Load fails, targets are not called. If Apply fails, the loaded settings are still returned alongside the error.
type DisplaySettings struct {
// Fullscreen puts the window in full screen on the chosen display, as the platform provides it (on macOS, native full screen in its own Space; on the web, the browser's full screen, granted only during a user gesture); false keeps it windowed.
Fullscreen bool `json:"fullscreen"`
// DisplayID is the ID, from core.Env.Displays, of the display full screen uses. It names a display the same way across launches and display changes, so a UI that offers displays sets it; when it is empty or the display is not connected, DisplayIndex chooses instead.
DisplayID string `json:"display_id,omitempty"`
// DisplayIndex is the position in core.Env.Displays of the display full screen uses when DisplayID is empty or not connected; out of range keeps the window's current display.
DisplayIndex int `json:"display_index"`
ScaleMode string `json:"scale_mode,omitempty"`
IntegerScale bool `json:"integer_scale"`
// FrameCap is the most frames drawn a second, uncapped when 0.
FrameCap int `json:"frame_cap"`
VSync bool `json:"vsync"`
// AutoDropLowPower lowers the frame cap while the system is in low-power mode or under serious thermal pressure, and restores it once the condition clears.
AutoDropLowPower bool `json:"auto_drop_low_power"`
// Quality is the player's quality setting as quality.NormalizeSetting writes it: "auto" (the default) lets quality.Selector choose from the device and its frame times, and "low", "medium" or "high" holds that preset.
Quality string `json:"quality,omitempty"`
}DisplaySettings holds player display and presentation preferences.
type Migration func(data json.RawMessage) (json.RawMessage, error)Migration converts a save's raw JSON data from one schema version to the next (v to v+1).
type Option func(*Store)Option configures a Store returned by NewStore, NewStorageStore or NewFileStore.
func WithMigration(from int, fn Migration) OptionWithMigration registers fn to migrate a save's JSON data from version from to from+1.
func WithMigrations(m map[int]Migration) OptionWithMigrations registers each migration in m, keyed by its starting version (from to from+1).
func WithVersion(v int) OptionWithVersion sets the store's current save schema version. Versions below 1 are treated as 1.
type Settings struct {
Audio AudioSettings `json:"audio"`
Bindings map[string][]string `json:"bindings,omitempty"`
Display DisplaySettings `json:"display"`
Locale string `json:"locale,omitempty"`
Accessibility AccessibilitySettings `json:"accessibility"`
Custom map[string]json.RawMessage `json:"custom,omitempty"`
}Settings holds typed, versioned player preferences kept completely separate from save slots.
func DefaultSettings() SettingsDefaultSettings returns a Settings populated with sane defaults.
func (s *Settings) Validate()Validate clamps out-of-range numeric fields and normalizes empty/whitespace strings in place.
type SettingsOption func(*settingsConfig)SettingsOption configures a SettingsStore or DefaultSettingsStore.
func WithSettingsMigration(from int, fn Migration) SettingsOptionWithSettingsMigration registers fn to migrate settings JSON data from version from to from+1.
func WithSettingsMigrations(m map[int]Migration) SettingsOptionWithSettingsMigrations registers each migration in m, keyed by its starting version (from to from+1).
func WithSettingsSchema(schema SettingsSchema) SettingsOptionWithSettingsSchema applies schema's Version and Migrations to a settings store.
func WithSettingsVersion(v int) SettingsOptionWithSettingsVersion sets the settings store's current schema version. Versions below 1 are treated as 1.
type SettingsSchema struct {
// Version is the current settings schema version written by Save and expected by Load; 1 when 0 or negative.
Version int
// Migrations maps a version v to the Migration that upgrades settings JSON data from v to v+1.
Migrations map[int]Migration
}SettingsSchema describes the version and step-by-step migrations for a SettingsStore.
type SettingsStore[T any] struct {
// Version is the current settings schema version written by Save and expected by Load; 1 when 0 or negative.
Version int
// Migrations maps a version v to the Migration that upgrades settings JSON data from v to v+1.
Migrations map[int]Migration
// contains filtered or unexported fields
}SettingsStore persists a versioned settings value of type T in a dedicated settings file or storage key, completely separate from save slots.
func NewSettingsStore[T any](backend Backend, defaults func() T, opts ...SettingsOption) *SettingsStore[T]NewSettingsStore returns a SettingsStore for T backed by backend.
defaults supplies the baseline value returned when no settings exist yet, used as the base when unmarshaling partial JSON, and written on Reset. When defaults is nil, DefaultSettings() is used if T is Settings, otherwise the zero value of T.
func (s *SettingsStore[T]) Delete() errorDelete removes the stored settings and its backup copy. Deleting absent settings returns nil.
func (s *SettingsStore[T]) Exists() boolExists reports whether a primary or backup settings payload exists.
func (s *SettingsStore[T]) Load() (T, error)Load reads settings, migrating older versions up to s.Version one step at a time and validating the result.
If no settings have been saved yet, Load returns the store's default value and a nil error. If the primary copy is missing, unreadable or corrupted, Load recovers from the backup copy. Settings from a newer schema version return ErrFutureVersion without falling back to an older backup.
func (s *SettingsStore[T]) RegisterMigration(from int, fn Migration)RegisterMigration registers fn to upgrade settings JSON data from version from to from+1.
func (s *SettingsStore[T]) Reset() errorReset restores and saves the store's default settings.
func (s *SettingsStore[T]) Save(value T) errorSave validates value (if T implements Validate()), encodes it into a versioned JSON envelope, and writes it atomically while keeping the previous valid copy as a backup.
type SettingsTargets struct {
// Sound receives master and group volumes from Settings.Audio.
// When Settings.Audio.Muted is true, the mixer's master volume is set to 0.
Sound *sound.Mixer
// SetMasterVolume receives the effective master volume (0 when Muted is true) in [0, 1].
SetMasterVolume func(volume float64)
// SetGroupVolume receives each audio group name and volume from Settings.Audio.Groups in sorted key order.
SetGroupVolume func(group string, volume float64)
// ApplyAudio receives the validated AudioSettings.
ApplyAudio func(AudioSettings) error
// ApplyBindings receives a cloned map of action bindings.
ApplyBindings func(map[string][]string) error
// ApplyDisplay receives the validated DisplaySettings.
ApplyDisplay func(DisplaySettings) error
// ApplyLocale receives the validated Locale string.
ApplyLocale func(locale string) error
// ApplyAccessibility receives the validated AccessibilitySettings.
ApplyAccessibility func(AccessibilitySettings) error
}SettingsTargets wires subsystems to receive loaded player settings at startup or when settings change. Every field is optional; nil targets are skipped.
type Store struct {
// Version is the current save schema version written by Save and expected by Load; 1 when 0 or negative.
Version int
// Migrations maps a version v to the Migration that upgrades a save's JSON data from v to v+1.
Migrations map[int]Migration
// contains filtered or unexported fields
}Store saves and loads versioned JSON game state across named slots backed by a Backend.
func NewFileStore(dir string, opts ...Option) *StoreNewFileStore returns a Store backed by JSON files inside dir (such as cx.DataDir()).
func NewStorageStore(store core.Storage, prefix string, opts ...Option) *StoreNewStorageStore returns a Store backed by store under keys starting with prefix.
func NewStore(backend Backend, opts ...Option) *StoreNewStore returns a Store backed by backend, defaulting to Version 1 before applying opts.
func (s *Store) Delete(slot string) errorDelete removes slot and its backup copy. Deleting a slot that does not exist returns nil. The backup goes first, so an interrupted Delete leaves either the whole slot or nothing that Load could resurrect.
func (s *Store) DeleteAll() errorDeleteAll removes every save slot and its backup copy. Player settings stored alongside save slots are never touched.
func (s *Store) Exists(slot string) boolExists reports whether slot has a stored save or backup copy.
func (s *Store) Load(slot string, dst any) errorLoad reads slot, migrates older save versions up to s.Version one step at a time, and unmarshals the data into dst.
If the primary copy is missing, unreadable or corrupted, Load automatically recovers from the slot's backup copy. It rewrites the primary from that backup only when the primary is missing or is not a JSON object at all (empty, truncated or garbage); a primary that failed to read for another reason, or that is a JSON object Load cannot use, is left as it is, because it may be newer than the backup. A save whose version exceeds s.Version returns an error wrapping ErrFutureVersion without falling back to an older backup, even when its envelope has fields this build does not know.
Load never writes a migrated save back: migrations run in memory on every Load until the slot is saved again, so each Migration must be a pure function of its input that gives the same result every time it runs.
An error about a copy's contents is a *loaderr.Error that names the copy, the line in the stored JSON and a fix. FileBackend names it by its file path (<dir>/<slot>.json, or <dir>/<slot>.json.bak for the backup) and StorageBackend by its storage key; another Backend by the slot, with " (backup)" for its backup copy.
func (s *Store) LoadChecked(slot string, dst any, check func() error) errorLoadChecked is Load with a check of the decoded value: after a copy decodes into dst, LoadChecked calls check, and a copy check refuses is treated as corrupted, so the backup is tried as it would be for one that does not decode.
Before the backup is decoded, and when LoadChecked returns an error, dst is put back to the value it had when LoadChecked was called, so nothing of a refused copy is left in it.
When check returns a *loaderr.Error whose Field is a path in dst's JSON, the error LoadChecked returns gives that field's line in the stored copy, under "data". A nil check checks nothing.
func (s *Store) RegisterMigration(from int, fn Migration)RegisterMigration registers fn to upgrade a save's JSON data from version from to from+1.
func (s *Store) Save(slot string, value any) errorSave encodes value into a versioned JSON envelope and writes it to slot.
Marshaling happens before the backend is touched, so an encoding error leaves any previous save in slot untouched.
func (s *Store) Slots() ([]string, error)Slots returns the sorted names of all slots stored in the backend.