SaveStore prüft jeden Schreibvorgang

Ein Speicherstand ersetzt den vorigen nur noch, wenn er vollständig
geschrieben und zurückgelesen wurde. Ein nicht gespeicherter
Spielerschlüssel wird gemeldet, und set_aside_save meldet, wenn nichts
verschoben wurde.

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
This commit is contained in:
Steven Wroblewski
2026-10-01 11:42:31 +02:00
parent ccf9813c80
commit 3761966303
2 changed files with 32 additions and 8 deletions
+13 -8
View File
@@ -25,7 +25,8 @@ func player_key() -> PackedByteArray:
var key := FileAccess.get_file_as_bytes(path)
if key.size() != KEY_BYTES:
key = Crypto.new().generate_random_bytes(KEY_BYTES)
_write(path, key)
if not _write(path, key):
push_error("player key could not be stored at %s" % path)
return key
@@ -37,24 +38,28 @@ func read_save() -> PackedByteArray:
return FileAccess.get_file_as_bytes(base_dir.path_join(SAVE_FILE))
## Writes the save through a temporary file, so that a crash while writing
## never destroys the previous save. Returns false if nothing was written.
## Writes the save through a temporary file, so that a crash or a failed
## write never destroys the previous save. Returns false if the new save was
## not stored completely; the previous save then stays as it was.
func write_save(bytes: PackedByteArray) -> bool:
if bytes.is_empty():
return false
var path := base_dir.path_join(SAVE_FILE)
var temporary := path + ".tmp"
if not _write(temporary, bytes):
if not _write(temporary, bytes) or FileAccess.get_file_as_bytes(temporary) != bytes:
DirAccess.remove_absolute(temporary)
return false
return DirAccess.rename_absolute(temporary, path) == OK
## Moves an unusable save out of the way, so that the next save does not
## overwrite it. An older set-aside save is replaced. Returns the new path.
## overwrite it. An older set-aside save is replaced. Returns the new path,
## or an empty text if there was no save or it could not be moved.
func set_aside_save() -> String:
var path := base_dir.path_join(SAVE_FILE)
var aside := path + ".broken"
DirAccess.rename_absolute(path, aside)
if DirAccess.rename_absolute(path, aside) != OK:
return ""
return aside
@@ -88,6 +93,6 @@ func _write(path: String, bytes: PackedByteArray) -> bool:
var file := FileAccess.open(path, FileAccess.WRITE)
if file == null:
return false
file.store_buffer(bytes)
var stored := file.store_buffer(bytes)
file.close()
return true
return stored