From b62f6c7d9b727e4a211592413cce3f09642c2330 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 20 Oct 2026 16:20:59 +0200 Subject: [PATCH 1/3] Test writing item name and quantity edits to a dfs file Port the commented-out C# test of ExamplesDfs2.ModifyDfs2ItemInfo, the example from issue #38, and test name and quantity edits on every dfs file type and way of opening it for editing. They fail on master, which never writes item info. Co-Authored-By: Claude Opus 5.5 --- tests/test_dfs2.py | 57 +++---- tests/test_dfs_edit.py | 352 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 376 insertions(+), 33 deletions(-) create mode 100644 tests/test_dfs_edit.py diff --git a/tests/test_dfs2.py b/tests/test_dfs2.py index 7fa1706..ec30b4c 100644 --- a/tests/test_dfs2.py +++ b/tests/test_dfs2.py @@ -243,39 +243,30 @@ def test_CreateOresundBathy900Test(self): # # dfs2File.Close(); - # def ModifyLanduseItemInfoTest(): - # - # originalFilename = "testdata/Landuse.dfs2"; - # filename = "testdata/testtmp/test_create_Landuse.dfs2"; - # - # File.Copy(originalFilename, filename, true); - # File.SetAttributes(filename, FileAttributes.Normal); # remove read-only flag - # - # # Check the new file - # - # file = DfsFileFactory.Dfs2FileOpen(filename); - # - # # Check existing data - # itemInfo = file.ItemInfo[0]; - # assert_equal("Landuse", itemInfo.Name); - # assert_equal(eumItem.eumIIntegerCode, itemInfo.Quantity.Item); - # assert_equal(eumUnit.eumUintCode, itemInfo.Quantity.Unit); - # - # file.Close(); - # - # # Method that modifies the Landuse.dfs2 file - # ExamplesDfs2.ModifyDfs2ItemInfo(filename); - # - # # Check the new file - # file = DfsFileFactory.Dfs2FileOpen(filename); - # - # # Check existing data - # itemInfo = file.ItemInfo[0]; - # assert_equal("GroundU", itemInfo.Name); - # assert_equal(eumItem.eumIAreaFraction, itemInfo.Quantity.Item); - # assert_equal(eumUnit.eumUPerCent, itemInfo.Quantity.Unit); - # - # file.Close(); + def test_ModifyLanduseItemInfoTest(self): + originalFilename = "testdata/Landuse.dfs2" + filename = "testdata/testtmp/test_modifyItemInfo_Landuse.dfs2" + + testUtil.copy_file(originalFilename, filename) + + # Check existing data + file = DfsFileFactory.Dfs2FileOpen(filename) + itemInfo = file.ItemInfo[0] + assert_equal("Landuse", itemInfo.Name) + assert_equal(eumItem.eumIIntegerCode, itemInfo.Quantity.Item) + assert_equal(eumUnit.eumUintCode, itemInfo.Quantity.Unit) + file.Close() + + # Method that modifies the Landuse.dfs2 file + ExamplesDfs2.ModifyDfs2ItemInfo(filename) + + # Check the new file + file = DfsFileFactory.Dfs2FileOpen(filename) + itemInfo = file.ItemInfo[0] + assert_equal("GroundU", itemInfo.Name) + assert_equal(eumItem.eumIAreaFraction, itemInfo.Quantity.Item) + assert_equal(eumUnit.eumUPerCent, itemInfo.Quantity.Unit) + file.Close() def test_ReadReshapedPastEndReturnsNone(self): dfsFile = DfsFileFactory.Dfs2FileOpen("testdata/OresundHD.dfs2") diff --git a/tests/test_dfs_edit.py b/tests/test_dfs_edit.py new file mode 100644 index 0000000..94b42c2 --- /dev/null +++ b/tests/test_dfs_edit.py @@ -0,0 +1,352 @@ +"""Editing item names and quantities, on every dfs file type and edit mode.""" + +import copy +import os +import shutil +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import numpy as np +import pytest + +from mikecore.DfsBuilder import DataValueType, DfsBuilder, DfsSimpleType +from mikecore.DfsFactory import DfsFactory +from mikecore.DfsFileFactory import DfsFileFactory +from mikecore.eum import eumItem, eumQuantity, eumUnit + + +@dataclass +class DfsType: + source: str + open: Callable[[Path], Any] + openEdit: Callable[[Path], Any] + openAppend: Callable[[Path], Any] + + +def createDfs1(filename): + # testdata has no dfs1 file + factory = DfsFactory() + builder = DfsBuilder.Create("title", "application", 1) + builder.SetDataType(0) + builder.SetGeographicalProjection(factory.CreateProjectionUndefined()) + builder.SetTemporalAxis(factory.CreateTemporalEqTimeAxis(eumUnit.eumUsec, 0, 60)) + builder.SetSpatialAxis(factory.CreateAxisEqD1(eumUnit.eumUmeter, 5, 0, 10)) + for name in ("Level", "Depth"): + item = builder.CreateDynamicItemBuilder() + item.Set( + name, + eumQuantity(eumItem.eumIWaterLevel, eumUnit.eumUmeter), + DfsSimpleType.Float, + ) + item.SetValueType(DataValueType.Instantaneous) + item.SetAxis(factory.CreateAxisEqD1(eumUnit.eumUmeter, 5, 0, 10)) + builder.AddDynamicItem(item.GetDynamicItemInfo()) + builder.CreateFile(filename) + file = builder.GetFile() + for timeStep in range(3): + for itemNumber in (1, 2): + data = np.arange(5, dtype=np.float32) + 10 * timeStep + itemNumber + file.WriteItemTimeStepNext(60.0 * timeStep, data) + file.Close() + + +F = DfsFileFactory +DFS_TYPES = { + "dfs0": DfsType( + "testdata/TemporalEqTime.dfs0", + F.DfsGenericOpen, + F.DfsGenericOpenEdit, + F.DfsGenericOpenAppend, + ), + "dfs1": DfsType("", F.Dfs1FileOpen, F.Dfs1FileOpenEdit, F.Dfs1FileOpenAppend), + "dfs2": DfsType( + "testdata/OresundHD.dfs2", + F.Dfs2FileOpen, + F.Dfs2FileOpenEdit, + F.Dfs2FileOpenAppend, + ), + "dfs3": DfsType( + "testdata/OresundHD.dfs3", + F.Dfs3FileOpen, + F.Dfs3FileOpenEdit, + F.Dfs3FileOpenAppend, + ), + "dfsu": DfsType( + "testdata/OresundHD.dfsu", + F.DfsuFileOpen, + F.DfsuFileOpenEdit, + F.DfsuFileOpenAppend, + ), +} + + +@dataclass +class Case: + path: Path + dfsType: DfsType + + +@pytest.fixture(params=list(DFS_TYPES)) +def case(request, tmp_path): + dfsType = DFS_TYPES[request.param] + path = tmp_path / ("test." + request.param) + if dfsType.source: + shutil.copyfile(dfsType.source, path) + os.chmod(path, 0o644) + else: + createDfs1(str(path)) + return Case(path, dfsType) + + +OPENERS = { + "edit": lambda case: case.dfsType.openEdit(case.path), + "append": lambda case: case.dfsType.openAppend(case.path), + "generic": lambda case: DfsFileFactory.DfsGenericOpenEdit(case.path), +} + +# Differs from the quantity of every item in the test files +NEW_ITEM = eumItem.eumIAreaFraction +NEW_UNIT = eumUnit.eumUPerCent + + +def readItems(path): + """(Name, eumItem, eumUnit) of each item.""" + file = DfsFileFactory.DfsGenericOpen(path) + items = [ + (itemInfo.Name, itemInfo.Quantity.Item, itemInfo.Quantity.Unit) + for itemInfo in file.ItemInfo + ] + file.Close() + return items + + +def readDynamicData(path): + """(time, data) of every item time step.""" + file = DfsFileFactory.DfsGenericOpen(path) + data = [] + while (itemData := file.ReadItemTimeStepNext()) is not None: + data.append((itemData.Time, itemData.Data.copy())) + file.Close() + return data + + +def firstNameInFile(path): + """The first item's name, its NUL-terminated bytes and their offset.""" + content = path.read_bytes() + name = readItems(path)[0][0] + nameBytes = name.encode("cp1252") + b"\0" + assert content.count(nameBytes) == 1 + return name, nameBytes, content.index(nameBytes) + + +@pytest.mark.parametrize("opener", list(OPENERS)) +def test_name_edit_is_written_to_that_item_only(case, opener): + data = readDynamicData(case.path) + expected = readItems(case.path) + # Another item is needed to check it stays unchanged + assert len(expected) > 1 + + for itemNo, (name, item, unit) in enumerate(readItems(case.path)): + file = OPENERS[opener](case) + file.ItemInfo[itemNo].Name = "Q" * len(name) + file.Close() + + expected[itemNo] = ("Q" * len(name), item, unit) + assert expected == readItems(case.path) + np.testing.assert_equal(data, readDynamicData(case.path)) + + +@pytest.mark.parametrize("opener", list(OPENERS)) +def test_quantity_edit_is_written_to_that_item_only(case, opener): + data = readDynamicData(case.path) + expected = readItems(case.path) + # Another item is needed to check it stays unchanged + assert len(expected) > 1 + + for itemNo, (name, _, _) in enumerate(readItems(case.path)): + file = OPENERS[opener](case) + file.ItemInfo[itemNo].Quantity = eumQuantity(NEW_ITEM, NEW_UNIT) + file.Close() + + expected[itemNo] = (name, NEW_ITEM, NEW_UNIT) + assert expected == readItems(case.path) + np.testing.assert_equal(data, readDynamicData(case.path)) + + +@pytest.mark.parametrize( + "length", + [ + pytest.param(lambda old: 0, id="empty"), + pytest.param(lambda old: 1, id="one"), + pytest.param(lambda old: old - 1, id="shorter"), + pytest.param(lambda old: old, id="same"), + pytest.param(lambda old: old + 5, id="longer"), + ], +) +def test_name_keeps_its_length_in_the_file(case, length): + """As in the C# library, a new name is padded or truncated to the old length.""" + data = readDynamicData(case.path) + oldName, oldBytes, offset = firstNameInFile(case.path) + newName = ("Ab" * len(oldName))[: length(len(oldName))] + + file = case.dfsType.openEdit(case.path) + itemInfo = file.ItemInfo[0] + itemInfo.Name = newName + file.Close() + + expected = newName[: len(oldName)].ljust(len(oldName)) + written = case.path.read_bytes()[offset : offset + len(oldBytes)] + assert expected.encode("cp1252") + b"\0" == written + assert expected == itemInfo.Name + assert expected == readItems(case.path)[0][0] + np.testing.assert_equal(data, readDynamicData(case.path)) + + +@pytest.mark.parametrize( + "attribute, value, error", + [ + pytest.param("Name", "Ω", UnicodeEncodeError, id="not-cp1252"), + pytest.param("Name", "A\0B", ValueError, id="nul"), + pytest.param( + "Quantity", + eumQuantity(eumItem.eumIWaterLevel, eumUnit.eumUPerCent), + ValueError, + id="unit-of-another-item", + ), + ], +) +@pytest.mark.parametrize("closeWith", ["flush", "close"]) +def test_rejected_value_changes_no_item(case, attribute, value, error, closeWith): + """ + A rejected value raises before anything is written, so the valid edit of + item 0 is not written either. Close still closes the file. + """ + original = case.path.read_bytes() + + file = case.dfsType.openEdit(case.path) + file.ItemInfo[0].Quantity = eumQuantity(NEW_ITEM, NEW_UNIT) + setattr(file.ItemInfo[1], attribute, value) + if closeWith == "flush": + with pytest.raises(error): + file.Flush() + with pytest.raises(error): + file.Close() + with pytest.raises(OSError): + file.Flush() + + assert original == case.path.read_bytes() + + +def test_read_mode_writes_nothing(case): + original = case.path.read_bytes() + + file = case.dfsType.open(case.path) + for itemInfo in file.ItemInfo: + itemInfo.Name = "abc" + itemInfo.Quantity = eumQuantity(NEW_ITEM, NEW_UNIT) + file.Close() + + # Not fitted to the stored length + assert "abc" == file.ItemInfo[0].Name + assert original == case.path.read_bytes() + + +def test_edit_after_close_writes_nothing(case): + original = case.path.read_bytes() + + file = case.dfsType.openEdit(case.path) + file.Close() + for itemInfo in file.ItemInfo: + itemInfo.Name = "abc" + itemInfo.Quantity = eumQuantity(NEW_ITEM, NEW_UNIT) + file.Close() + with pytest.raises(OSError): + file.Flush() + + assert original == case.path.read_bytes() + + +def test_quantity_changed_in_place_is_not_written(case): + """As in the C# library, only assigning a new Quantity writes it.""" + original = case.path.read_bytes() + + file = case.dfsType.openEdit(case.path) + for itemInfo in file.ItemInfo: + itemInfo.Quantity.Item = NEW_ITEM + itemInfo.Quantity.Unit = NEW_UNIT + file.Close() + + assert original == case.path.read_bytes() + + +def test_item_put_in_item_info_is_not_written(case): + """Only items read from the file are written, not replacements.""" + original = case.path.read_bytes() + + file = case.dfsType.openEdit(case.path) + itemInfo = copy.copy(file.ItemInfo[0]) + file.ItemInfo[0] = itemInfo + itemInfo.Quantity = eumQuantity(NEW_ITEM, NEW_UNIT) + file.Close() + + assert original == case.path.read_bytes() + + +def test_flush_then_append(case): + """Writing item edits on Flush does not move the append position.""" + data = [values for _, values in readDynamicData(case.path)] + items = readItems(case.path) + name, item, unit = items[0] + + file = case.dfsType.openAppend(case.path) + file.ItemInfo[0].Name = "Q" * len(name) + file.Flush() + # Differs from the first time step, so overwriting it would show + appended = data[-len(items) :] + assert not np.array_equal(appended[0], data[0]) + for values in appended: + file.WriteItemTimeStepNext(0.0, values) + file.Close() + + newData = [values for _, values in readDynamicData(case.path)] + np.testing.assert_equal(data + appended, newData) + assert [("Q" * len(name), item, unit), *items[1:]] == readItems(case.path) + + +def test_quantity_edit_keeps_a_name_cp1252_cannot_decode(case): + """ + A Quantity-only edit writes back unchanged a name cp1252 cannot decode, + such as UTF-8 from another tool. + """ + _, oldBytes, offset = firstNameInFile(case.path) + # 0x81 is undefined in cp1252 + nameBytes = b"\x81" + oldBytes[1:] + with open(case.path, "r+b") as f: + f.seek(offset) + f.write(nameBytes) + assert "�" == readItems(case.path)[0][0][0] + data = readDynamicData(case.path) + + file = case.dfsType.openEdit(case.path) + file.ItemInfo[0].Quantity = eumQuantity(NEW_ITEM, NEW_UNIT) + file.Close() + + written = case.path.read_bytes()[offset : offset + len(nameBytes)] + assert nameBytes == written + assert (NEW_ITEM, NEW_UNIT) == readItems(case.path)[0][1:] + np.testing.assert_equal(data, readDynamicData(case.path)) + + +def test_flush_writes_the_edit_in_edit_mode(case): + """Not Append mode: there the native library writes the header only on Close.""" + oldName, oldBytes, offset = firstNameInFile(case.path) + + file = case.dfsType.openEdit(case.path) + file.ItemInfo[0].Name = "Q" * len(oldName) + file.Flush() + written = case.path.read_bytes()[offset : offset + len(oldBytes)] + file.Close() + + assert ("Q" * len(oldName)).encode("cp1252") + b"\0" == written From c10b9fa266329c41331eadacadc4daf26d8b6858 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 20 Oct 2026 16:21:00 +0200 Subject: [PATCH 2/3] Fix DfsuFile.Flush and let DfsuFileOpenAppend default its parameters DfsuFile.Flush passed itself to DfsFile.Flush, which takes no argument, so it raised TypeError. DfsuFileOpenAppend was the only Open method that required parameters. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +++ mikecore/DfsFileFactory.py | 2 +- mikecore/DfsuFile.py | 2 +- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 378023b..01b11be 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -69,6 +69,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 engine in the same process loaded first (#45). - `uv build --wheel` works with hatchling 1.31 and later, and the wheel holds each native library once. It held each one twice before. +- `DfsuFile.Flush()` flushes the file instead of raising `TypeError`, and + `DfsFileFactory.DfsuFileOpenAppend` no longer requires `parameters`, like the + other `Open` methods. - Items read from a dfs file have the reference coordinates and orientation stored in the file. They had the `-1e-35` defaults, whatever the file held ([#31](https://github.com/DHI/mikecore-python/issues/31)). diff --git a/mikecore/DfsFileFactory.py b/mikecore/DfsFileFactory.py index b7a132d..302b136 100644 --- a/mikecore/DfsFileFactory.py +++ b/mikecore/DfsFileFactory.py @@ -71,7 +71,7 @@ def DfsuFileOpenEdit(filename, parameters=None): return DfsuFile(dfsFile) @staticmethod - def DfsuFileOpenAppend(filename, parameters): + def DfsuFileOpenAppend(filename, parameters=None): dfsFile = DfsFileFactory.DfsGenericOpenAppend(filename, parameters) return DfsuFile(dfsFile) diff --git a/mikecore/DfsuFile.py b/mikecore/DfsuFile.py index 2bbcf39..569d14b 100644 --- a/mikecore/DfsuFile.py +++ b/mikecore/DfsuFile.py @@ -382,7 +382,7 @@ def Reset(self): self.dfsFile.Reset() def Flush(self): - self.dfsFile.Flush(self) + self.dfsFile.Flush() def FlushTimeStep(self): self.dfsFile.FlushTimeStep() From eabf585e95314e522277dcea5129db94c0b53940 Mon Sep 17 00:00:00 2001 From: Ryan Murray Date: Tue, 20 Oct 2026 16:21:01 +0200 Subject: [PATCH 3/3] Write item name and quantity edits on Flush and Close In a file opened for editing, the file remembers the dynamic items it read. Flush and Close write the ones whose Name changed or that were assigned a new Quantity, through dfsUpdateItemInfo. As in the C# library, a new name is truncated or padded to the stored length, and a Quantity changed in place is not written. Every change is checked before any is written, and Close still closes the file when it raises. Closes #38 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 +++++ mikecore/DfsDLL.py | 8 ++++ mikecore/DfsFile.py | 89 ++++++++++++++++++++++++++++++++++++++++++--- 3 files changed, 101 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 01b11be..69eaeed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -69,6 +69,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 engine in the same process loaded first (#45). - `uv build --wheel` works with hatchling 1.31 and later, and the wheel holds each native library once. It held each one twice before. +- In a dfs file opened for editing, a dynamic item's changed `Name` or newly + assigned `Quantity` is written to the file on `Close`, and in Edit mode + also on `Flush`. As in the + C# library, a new name is truncated or padded with spaces to the length of + the old one, and changing `Quantity.Item` or `Quantity.Unit` in place is not + written. A name that cp1252 cannot encode raises `UnicodeEncodeError`, and + a name containing a NUL character or a unit that is not a unit of the item + raises `ValueError`, before any item is written + ([#38](https://github.com/DHI/mikecore-python/issues/38)). - `DfsuFile.Flush()` flushes the file instead of raising `TypeError`, and `DfsFileFactory.DfsuFileOpenAppend` no longer requires `parameters`, like the other `Open` methods. diff --git a/mikecore/DfsDLL.py b/mikecore/DfsDLL.py index 0f4ec3e..0b48b02 100644 --- a/mikecore/DfsDLL.py +++ b/mikecore/DfsDLL.py @@ -207,6 +207,14 @@ def Init(libfilepath: str | None = None): ctypes.c_void_p, ctypes.c_void_p, ] + lib.dfsUpdateItemInfo.argtypes = [ + ctypes.c_void_p, + ctypes.c_void_p, + ctypes.c_int32, + ctypes.c_char_p, + ctypes.c_int32, + ] + lib.dfsUpdateItemInfo.restype = ctypes.c_int32 lib.dfsAddCustomBlock.argtypes = [ ctypes.c_void_p, diff --git a/mikecore/DfsFile.py b/mikecore/DfsFile.py index a58a01d..e5292c2 100644 --- a/mikecore/DfsFile.py +++ b/mikecore/DfsFile.py @@ -779,6 +779,8 @@ def __init__(self): self.fpTimeStepIndex = 0 self.headPointer = ctypes.c_void_p(0) self.filePointer = ctypes.c_void_p(0) + # (item, Quantity it was read with), only for files opened for editing + self.__itemsRead = [] def __del__(self): self.Close() @@ -862,6 +864,8 @@ def Open(self, filename, mode=DfsFileMode.Read, parameters=None): self.ItemInfo = [] for i in range(noOfItems): self.ItemInfo.append(self.__DynamicItemInfoReadAndCreate(i + 1, noOfItems)) + if mode != DfsFileMode.Read: + self.__itemsRead = [(item, item.Quantity) for item in self.ItemInfo] if mode == DfsFileMode.Read: # file pointer is after header part @@ -901,13 +905,66 @@ def Close(self): """ Close the file and release all ressources associated with it. The header information is still valid (for reading) even though the file has been closed. + + Writes item edits first, see Flush. The file is closed even if that + raises. """ - if self.filePointer.value is not None: - DfsDLL.Wrapper.dfsFileClose( - self.headPointer, ctypes.byref(self.filePointer) + try: + self.__WriteItemInfo() + finally: + self.__itemsRead = [] + if self.filePointer.value is not None: + DfsDLL.Wrapper.dfsFileClose( + self.headPointer, ctypes.byref(self.filePointer) + ) + if self.headPointer.value is not None: + DfsDLL.Wrapper.dfsHeaderDestroy(ctypes.byref(self.headPointer)) + + def __WriteItemInfo(self): + """ + Write changed dynamic item Names and Quantities. As in the C# library, + only an assigned Quantity counts, not one changed in place, and a new + name is fitted to the stored name's length. All changes are checked + before any is written. + """ + changes = [] + for item, quantityRead in self.__itemsRead: + nameBytes = DfsDLLUtil.GetItemNameBytes(item.ItemPointer) + nameChanged = item.Name != nameBytes.decode("cp1252", "replace") + if not nameChanged and item.Quantity is quantityRead: + continue + if nameChanged: + # The native library reads the name up to the first NUL + if "\0" in item.Name: + raise ValueError( + f"Name of item {item.ItemNumber} contains a NUL character: " + f"{item.Name!r}" + ) + try: + newNameBytes = item.Name.encode("cp1252") + except UnicodeEncodeError as error: + error.add_note(f"Name of item {item.ItemNumber}: {item.Name!r}") + raise + length = len(nameBytes) + nameBytes = newNameBytes[:length].ljust(length, b" ") + quantity = item.Quantity + if not eumWrapper.eumItemUnitEqv(quantity.Item, quantity.Unit): + raise ValueError( + f"Item {item.ItemNumber} has a Quantity whose unit " + f"{quantity.Unit!r} is not a unit of {quantity.Item!r}" + ) + changes.append((item, nameBytes, quantity)) + for item, nameBytes, quantity in changes: + rok = DfsDLL.Wrapper.dfsUpdateItemInfo( + self.headPointer, + item.ItemPointer, + ctypes.c_int32(quantity.Item), + nameBytes, + ctypes.c_int32(quantity.Unit), ) - if self.headPointer.value is not None: - DfsDLL.Wrapper.dfsHeaderDestroy(ctypes.byref(self.headPointer)) + DfsDLL.CheckReturnCode(rok) + item.Name = nameBytes.decode("cp1252", "replace") + self.__itemsRead = [(item, item.Quantity) for item, _ in self.__itemsRead] def GetNextItemNumber(self): return self.fpItemNumber @@ -1303,8 +1360,13 @@ def Flush(self): Flush cached data to the file. This will especially update the header information, such that if another process is reading the file while it is being read, the new header information can be retrieved. + + Writes dynamic item Name and Quantity edits first; if one is rejected, + none is written. In Append mode the native library writes the header + only on Close. """ self.__CheckIfOpen() + self.__WriteItemInfo() DfsDLL.Wrapper.dfsFileFlush(self.headPointer, self.filePointer) def FlushTimeStep(self): @@ -1579,6 +1641,23 @@ class DfsDLLUtil: """Utilities class, marshalling values to and from the DFS native library, and creating various Dfs classes based on pointers to DFS native data""" + @staticmethod + def GetItemNameBytes(itemPointer) -> bytes: + """The undecoded name bytes of an item.""" + itemNameP = ctypes.c_char_p() + DfsDLL.Wrapper.dfsGetItemInfo( + itemPointer, + ctypes.byref(ctypes.c_int32()), + ctypes.byref(ctypes.c_char_p()), + ctypes.byref(itemNameP), + ctypes.byref(ctypes.c_int32()), + ctypes.byref(ctypes.c_char_p()), + ctypes.byref(ctypes.c_int()), + ) + if itemNameP.value is None: + raise ValueError("Native library returned a null string") + return itemNameP.value + @staticmethod def EncodeFileName(filename: str | os.PathLike[str]) -> bytes: # The native library opens char* paths, which Windows interprets in the