OpenSWMM Engine  6.0.0-alpha.4
Data-oriented, plugin-extensible SWMM Engine (6.0.0-alpha.4)
Loading...
Searching...
No Matches
openswmm::io Namespace Reference

Namespaces

namespace  detail
 

Classes

class  AtomicOutputFile
 Own a staging stream and publish it by a checked single-file rename. More...
 
class  CheckpointDirectory
 
struct  CheckpointFile
 
class  CheckpointOutputPublication
 
struct  OwnedCheckpointFile
 
struct  RelativeResult
 Outcome of computing target relative to anchor_dir. More...
 

Enumerations

enum class  PathClass : int {
  Relative = 0 ,
  AbsoluteSameVolume = 1 ,
  AbsoluteCrossVolume = 2 ,
  Invalid = 3
}
 Classification of a makeRelative() result. More...
 

Functions

std::filesystem::path utf8_path (const std::string &utf8)
 Convert borrowed path bytes into an owned native filesystem path.
 
template<class P>
requires std::same_as<std::remove_cvref_t<P>, std::filesystem::path>
std::filesystem::path utf8_path (P &&)=delete
 Passing an fs::path to utf8_path() is always a mistake — refuse it at compile time, on EVERY platform.
 
std::string path_utf8 (const std::filesystem::path &p, bool generic=false)
 Copy a native path into the engine byte-string representation.
 
template<class S>
requires (!std::same_as<std::remove_cvref_t<S>, std::filesystem::path>)
std::string path_utf8 (S &&, bool=false)=delete
 The mirror guard: path_utf8() takes a path, never a string.
 
std::FILE * fopen_path (const std::filesystem::path &p, const char *mode)
 Open a borrowed native path using platform C stdio.
 
std::FILE * fopen_utf8 (const std::string &utf8, const char *mode)
 Convert engine path bytes and open a C stdio stream.
 
bool isAbsolutePath (const std::string &path) noexcept
 Recognize platform-neutral absolute-looking path syntax.
 
std::string normaliseSeparators (const std::string &path)
 Normalize separator and dot spelling without resolving parent segments.
 
std::string parentDir (const std::string &file_path)
 Extract a directory token using normalized separator text.
 
std::string resolveRelative (const std::string &stored_token, const std::string &anchor_dir)
 Join a stored token to a directory anchor using lexical normalization.
 
RelativeResult makeRelative (const std::string &target_absolute, const std::string &anchor_dir, int max_up_levels=16)
 Compute a lexical relative token or return a classified absolute fallback.
 
bool checkpointNoReplaceAvailable () noexcept
 Report compile-time support for exclusive checkpoint publication.
 
void publishCheckpointNoReplace (const std::filesystem::path &staging, const std::filesystem::path &destination)
 Atomically publish a private file/directory without replacing any destination.
 
uint64_t checkpointFileSize (const std::filesystem::path &path)
 Read a checkpoint companion's validated size.
 
void checkpointSeek (FILE *f, uint64_t offset)
 Position an existing stream at an absolute checkpoint byte offset.
 
std::shared_ptr< OwnedCheckpointFile > copyCheckpointFile (const std::filesystem::path &source, uint64_t bytes, const std::filesystem::path &staging_base, int source_descriptor=-1)
 Copy and verify an exact source prefix into a private companion file.
 
hid_t checkpointHdf5Access ()
 Create access properties using the locked native-descriptor checkpoint VFD.
 
hid_t createCheckpointHdf5 (const char *path, unsigned flags)
 Create a checkpoint-compatible HDF5 result file.
 
hid_t openCheckpointHdf5 (const char *path, unsigned flags)
 Open a checkpoint-compatible HDF5 result file.
 
int checkpointHdf5Descriptor (hid_t file)
 Borrow the native descriptor of a sec2 or checkpoint-VFD file.
 
FILE * checkpointOpenOutput (const std::filesystem::path &path, bool existing=false)
 Open a writable binary output for checkpoint restoration.
 
int checkpointFileDescriptor (FILE *stream) noexcept
 Obtain a borrowed platform descriptor for a C stream.
 
void checkpointReadOutput (int descriptor, uint64_t offset, char *data, std::size_t bytes)
 Read an exact output range through a borrowed seekable writer descriptor.
 
std::recursive_mutex & resultHdf5Mutex ()
 Access the shared recursive lock for result-file HDF5 operations.
 
hid_t createHdf5Dataset (hid_t location, const char *name, hid_t type, hid_t space, hid_t links, hid_t creation, hid_t access)
 Create a dataset without wall-clock object timestamps.
 
hid_t createHdf5Group (hid_t location, const char *name, hid_t links, hid_t creation, hid_t access)
 Create a group without wall-clock object timestamps.
 
hid_t createHdf5File (const char *path, unsigned flags, hid_t creation, hid_t access)
 Create an HDF5 file without wall-clock object timestamps.
 

Enumeration Type Documentation

◆ PathClass

enum class openswmm::io::PathClass : int
strong

Classification of a makeRelative() result.

Callers use this to decide whether the produced string is usable as a portable token in a .inp file. Only Relative is portable; the absolute variants are returned when the relative form would be invalid or worse than the absolute one.

Enumerator
Relative 

Expressible relative to anchor; portable.

AbsoluteSameVolume 

Different sub-tree, same root/drive; not portable across folder layouts but still on the same volume.

AbsoluteCrossVolume 

Different drive / UNC / mount point; not portable across machines without identical mounts.

Invalid 

Empty or malformed input.

Function Documentation

◆ checkpointFileDescriptor()

int openswmm::io::checkpointFileDescriptor ( FILE * stream)
noexcept

Obtain a borrowed platform descriptor for a C stream.

Parameters
[in]streamBorrowed open C stream, or null.
Returns
Its CRT/POSIX descriptor, or -1 for null or descriptor failure.
Note
The stream retains ownership; the caller must not independently close the returned descriptor.

◆ checkpointFileSize()

uint64_t openswmm::io::checkpointFileSize ( const std::filesystem::path & path)

Read a checkpoint companion's validated size.

Parameters
[in]pathBorrowed non-symlink regular file to inspect.
Returns
Length in bytes, in [1, INT64_MAX].
Exceptions
std::runtime_errorFile type or size is invalid.
std::filesystem::filesystem_errorMetadata inspection fails.
Here is the caller graph for this function:

◆ checkpointHdf5Access()

hid_t openswmm::io::checkpointHdf5Access ( )

Create access properties using the locked native-descriptor checkpoint VFD.

Serializes registration/property creation through resultHdf5Mutex. The VFD uses native descriptors with shared/exclusive nonblocking file locks; Windows opens with FILE_SHARE_DELETE so checkpoint publication can rename an open result file. Callers serialize subsequent HDF5 operations using the same mutex; file objects retain their own properties after this list closes.

Returns
Owned H5P_FILE_ACCESS identifier to close with H5Pclose, or H5I_INVALID_HID when registration/property setup fails.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ checkpointHdf5Descriptor()

int openswmm::io::checkpointHdf5Descriptor ( hid_t file)

Borrow the native descriptor of a sec2 or checkpoint-VFD file.

Serializes metadata lookup with resultHdf5Mutex. Does not duplicate the descriptor: do not close it independently, and do not use it after the HDF5 file closes. The lock is released before return; caller must coordinate later descriptor IO with HDF5 file operations. May register the checkpoint driver while comparing VFD kinds.

Parameters
[in]fileBorrowed live HDF5 file identifier; caller keeps it open throughout descriptor use.
Returns
Borrowed descriptor value, or -1 when file/access lookup fails or the VFD is unsupported.
Here is the call graph for this function:

◆ checkpointNoReplaceAvailable()

bool openswmm::io::checkpointNoReplaceAvailable ( )
noexcept

Report compile-time support for exclusive checkpoint publication.

Returns
True for Windows, macOS, or Linux builds exposing SYS_renameat2; false otherwise. This does not probe runtime filesystem support.
Here is the caller graph for this function:

◆ checkpointOpenOutput()

FILE * openswmm::io::checkpointOpenOutput ( const std::filesystem::path & path,
bool existing = false )

Open a writable binary output for checkpoint restoration.

Parameters
[in]pathBorrowed output path in platform filesystem encoding.
[in]existingTrue opens an existing file without truncation; false exclusively creates a new file and fails if the path exists.
Returns
Owned read/write stream, positioned at the beginning, or null on open/wrapping failure. The caller must eventually fclose() a returned stream.
Note
Windows opens with delete/rename sharing so publication may replace the live file while its original stream remains open.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ checkpointReadOutput()

void openswmm::io::checkpointReadOutput ( int descriptor,
uint64_t offset,
char * data,
std::size_t bytes )

Read an exact output range through a borrowed seekable writer descriptor.

Parameters
[in]descriptorNonnegative open readable seekable descriptor, flushed and exclusively held by the caller for the complete operation; never closed or retained by this helper.
[in]offsetAbsolute byte offset in [0, INT64_MAX], with offset+bytes <= INT64_MAX.
[out]dataWritable storage for at least bytes bytes; null permitted only for zero bytes. May contain a copied prefix if reading or final position restoration fails.
[in]bytesExact byte count; zero still checks/repositions/restores the descriptor.
Exceptions
std::runtime_errorInvalid range, failed initial seek/read (including early EOF), or failed final restoration. EINTR reads retry; already copied bytes are not rolled back.

Saves the original file position, seeks and reads in at most INT_MAX chunks, then attempts to restore the saved offset even after failed reads. A restoration failure is reported, so the original position is not guaranteed on failure. Does not flush a C/HDF5 writer, lock the descriptor, validate source identity or advance simulation. This avoids opening another handle under Windows mandatory file locking.

◆ checkpointSeek()

void openswmm::io::checkpointSeek ( FILE * f,
uint64_t offset )

Position an existing stream at an absolute checkpoint byte offset.

Parameters
[in,out]fNon-null open seekable stream, borrowed and not closed.
[in]offsetAbsolute byte offset in [0, INT64_MAX]; seeking beyond the current end is allowed when supported by the underlying stream.
Exceptions
std::runtime_errorThe stream or offset is invalid, or seeking fails.
Note
This does not clear existing stream error flags or validate file length.

◆ copyCheckpointFile()

std::shared_ptr< OwnedCheckpointFile > openswmm::io::copyCheckpointFile ( const std::filesystem::path & source,
uint64_t bytes,
const std::filesystem::path & staging_base,
int source_descriptor = -1 )

Copy and verify an exact source prefix into a private companion file.

Copy exactly a known prefix; validate the copy again before publication. Exclusive creation and ownership ensure failures cannot remove other files. A supplied descriptor is borrowed from a flushed, exclusively held writer; its position is preserved, avoiding a second handle under mandatory locks.

Parameters
[in]sourceNon-symlink regular source file, read from byte zero.
[in]bytesPrefix length in [1, source file size], no larger than INT64_MAX.
[in]staging_baseBase path for exclusive sibling names ending in .file-part-N; its parent must exist and permit file creation.
[in]source_descriptorBorrowed seekable descriptor for the same source file, or -1 to open source independently. Caller must flush/exclusively hold a supplied writer; its offset is preserved. The descriptor/file identity is a caller precondition, not independently checked.
Returns
Shared cleanup owner for a flushed, synchronized, closed and fingerprint-verified private copy. Call retain() only when removal ownership has been transferred; otherwise the last owner's destruction removes it.
Exceptions
std::runtime_errorValidation, opening, copying, synchronization, closing, verification or all 32 exclusive reservations fail. Filesystem and allocation exceptions may propagate. Partial owned copies are cleaned up.
Note
The source is not locked; concurrent modifications can invalidate the copy contract and are the caller's responsibility.
Here is the call graph for this function:

◆ createCheckpointHdf5()

hid_t openswmm::io::createCheckpointHdf5 ( const char * path,
unsigned flags )

Create a checkpoint-compatible HDF5 result file.

Creation disables wall-clock object timestamps for deterministic checkpoint images. Serializes this operation with resultHdf5Mutex, uses the checkpoint VFD on Windows and default HDF5 access on POSIX. Temporary access properties are released before return. Caller must serialize later HDF5 operations and own the returned file lifetime; opening/creating does not retain caller path storage.

Parameters
[in]pathNon-null null-terminated filename, borrowed for the call; UTF-8 on Windows.
[in]flagsH5Fcreate flags, such as H5F_ACC_TRUNC or H5F_ACC_EXCL; determine replacement/exclusive-create behavior.
Returns
Owned HDF5 file identifier to close with H5Fclose, or a negative identifier on failure.
Here is the call graph for this function:

◆ createHdf5Dataset()

hid_t openswmm::io::createHdf5Dataset ( hid_t location,
const char * name,
hid_t type,
hid_t space,
hid_t links,
hid_t creation,
hid_t access )
inline

Create a dataset without wall-clock object timestamps.

Parameters
[in]locationBorrowed file or group identifier for the new link.
[in]nameNon-null null-terminated dataset path, borrowed for this call.
[in]typeBorrowed HDF5 datatype identifier.
[in]spaceBorrowed dataspace defining the dataset shape.
[in]linksBorrowed link-creation properties or H5P_DEFAULT.
[in]creationBorrowed dataset-creation properties or H5P_DEFAULT; copied before disabling timestamp tracking.
[in]accessBorrowed dataset-access properties or H5P_DEFAULT.
Returns
Owned dataset identifier to close with H5Dclose(), or a negative value on failure. No input identifier or pointer is retained.
Here is the call graph for this function:

◆ createHdf5File()

hid_t openswmm::io::createHdf5File ( const char * path,
unsigned flags,
hid_t creation,
hid_t access )
inline

Create an HDF5 file without wall-clock object timestamps.

Parameters
[in]pathNon-null null-terminated destination filename.
[in]flagsH5Fcreate access flags, such as H5F_ACC_TRUNC or H5F_ACC_EXCL.
[in]creationBorrowed file-creation properties or H5P_DEFAULT; copied before disabling timestamp tracking.
[in]accessBorrowed file-access properties or H5P_DEFAULT.
Returns
Owned file identifier to close with H5Fclose(), or a negative value on failure. Existing-file handling follows flags; no input is retained.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ createHdf5Group()

hid_t openswmm::io::createHdf5Group ( hid_t location,
const char * name,
hid_t links,
hid_t creation,
hid_t access )
inline

Create a group without wall-clock object timestamps.

Parameters
[in]locationBorrowed file or group identifier for the new link.
[in]nameNon-null null-terminated group path, borrowed for this call.
[in]linksBorrowed link-creation properties or H5P_DEFAULT.
[in]creationBorrowed group-creation properties or H5P_DEFAULT; copied before disabling timestamp tracking.
[in]accessBorrowed group-access properties or H5P_DEFAULT.
Returns
Owned group identifier to close with H5Gclose(), or a negative value on failure. No input identifier or pointer is retained.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ fopen_path()

std::FILE * openswmm::io::fopen_path ( const std::filesystem::path & p,
const char * mode )
inline

Open a borrowed native path using platform C stdio.

Windows widens the ASCII mode and invokes _wfopen; POSIX calls fopen. Mode may truncate/create the destination. C-runtime errors use errno; allocations for the Windows mode string may throw.

Parameters
[in]pBorrowed native filesystem path.
[in]modeNon-null NUL-terminated ASCII fopen mode; must be valid for the platform C runtime.
Returns
Owned FILE stream on success or nullptr for C-runtime open failure; caller closes with fclose().
Here is the caller graph for this function:

◆ fopen_utf8()

std::FILE * openswmm::io::fopen_utf8 ( const std::string & utf8,
const char * mode )
inline

Convert engine path bytes and open a C stdio stream.

Path conversion/allocation exceptions propagate. Opening can create/truncate according to mode.

Parameters
[in]utf8Borrowed UTF-8 Windows path or native POSIX path bytes.
[in]modeNon-null NUL-terminated ASCII stdio mode, passed to fopen_path().
Returns
Owned FILE stream, or nullptr on open failure; caller must fclose() once.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ isAbsolutePath()

bool openswmm::io::isAbsolutePath ( const std::string & path)
noexcept

Recognize platform-neutral absolute-looking path syntax.

Drive-relative C:folder is deliberately classified as absolute-looking here, unlike native Windows filesystem semantics. No filesystem lookup or validity checking.

Parameters
[in]pathBorrowed byte string; no separator normalization is performed.
Returns
True for leading slash, alphabetic drive-colon prefix or two leading slash/backslash separators; false for empty/relative syntax.
Here is the caller graph for this function:

◆ makeRelative()

RelativeResult openswmm::io::makeRelative ( const std::string & target_absolute,
const std::string & anchor_dir,
int max_up_levels = 16 )

Compute a lexical relative token or return a classified absolute fallback.

Pure lexical operation: does not resolve symlinks, check existence or detect POSIX mount boundaries. Recognizes drive/UNC roots across hosts and compares the entire root case-insensitively using C-locale lowercase. Empty anchor returns normalized target with AbsoluteSameVolume for recognized absolute syntax, otherwise Invalid. Relative output uses forward slashes and preserves authored relative geometry. Allocation/encoding exceptions propagate.

Parameters
[in]target_absoluteBorrowed target text expected absolute; an empty target is Invalid. Nonempty relative text is not independently rejected when an anchor exists.
[in]anchor_dirBorrowed directory token. It is always treated as a directory; no file-type detection or automatic parent extraction occurs.
[in]max_up_levelsMaximum permitted leading parent segments, default 16; negative values force absolute fallback even for zero parent segments.
Returns
Owned path/classification/warning result; Relative sets up_levels, fallback results leave it zero.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ normaliseSeparators()

std::string openswmm::io::normaliseSeparators ( const std::string & path)

Normalize separator and dot spelling without resolving parent segments.

Text cleanup only: does not consult files, resolve parent segments or promise native canonical form. Drive/UNC root-shaped strings receive special trailing-slash preservation.

Parameters
[in]pathBorrowed path-like byte string; empty stays empty.
Returns
Owned string with backslashes changed to slash, repeated slash runs collapsed except leading UNC marker, and redundant slash-dot forms/trailing separators trimmed.
Here is the caller graph for this function:

◆ openCheckpointHdf5()

hid_t openswmm::io::openCheckpointHdf5 ( const char * path,
unsigned flags )

Open a checkpoint-compatible HDF5 result file.

Serializes this operation with resultHdf5Mutex, uses the checkpoint VFD on Windows and default HDF5 access on POSIX. Temporary access properties are released before return. Caller must serialize later HDF5 operations and own the returned file lifetime; opening/creating does not retain caller path storage.

Parameters
[in]pathNon-null null-terminated filename, borrowed for the call; UTF-8 on Windows.
[in]flagsH5Fopen access flags, normally H5F_ACC_RDONLY or H5F_ACC_RDWR.
Returns
Owned HDF5 file identifier to close with H5Fclose, or a negative identifier on failure.
Here is the call graph for this function:

◆ parentDir()

std::string openswmm::io::parentDir ( const std::string & file_path)

Extract a directory token using normalized separator text.

Does not inspect filesystem object type: an actual directory without a trailing separator is treated like a filename. Recognized drive/root prefixes are preserved.

Parameters
[in]file_pathBorrowed token. A trailing slash/backslash explicitly marks a directory; otherwise the final component is treated as a filename.
Returns
Owned normalized directory token, or empty for no parent/empty input.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ path_utf8() [1/2]

std::string openswmm::io::path_utf8 ( const std::filesystem::path & p,
bool generic = false )
inline

Copy a native path into the engine byte-string representation.

No filesystem lookup. Allocation/encoding exceptions propagate; use utf8_path() explicitly before passing byte strings here.

Parameters
[in]pBorrowed native filesystem path, already constructed using the intended encoding.
[in]genericTrue selects generic slash separators, false native formatting.
Returns
Owned UTF-8 bytes on Windows; native byte-preserving string on POSIX.
Here is the caller graph for this function:

◆ path_utf8() [2/2]

template<class S>
requires (!std::same_as<std::remove_cvref_t<S>, std::filesystem::path>)
std::string openswmm::io::path_utf8 ( S && ,
bool = false )
delete

The mirror guard: path_utf8() takes a path, never a string.

A std::string or const char* argument would silently construct the fs::path parameter from the NATIVE NARROW encoding — the ANSI code page on Windows — which is issue #7 itself, arrived at through the very helper meant to prevent it, and again visible only on MSVC. Convert explicitly with utf8_path() first if that is genuinely what was meant.

◆ publishCheckpointNoReplace()

void openswmm::io::publishCheckpointNoReplace ( const std::filesystem::path & staging,
const std::filesystem::path & destination )

Atomically publish a private file/directory without replacing any destination.

Atomically rename a staged checkpoint without replacing a destination.

Parameters
[in]stagingExisting private file or directory to move; must be on a filesystem where the platform's no-replace rename can succeed.
[in]destinationFinal path, which must not already exist.
Exceptions
std::runtime_errorPublication fails or no supported platform primitive is compiled in. Paths remain caller-owned.
Note
The platform operation protects even an existing empty directory. No copy fallback or cross-filesystem publication is performed.
Here is the caller graph for this function:

◆ resolveRelative()

std::string openswmm::io::resolveRelative ( const std::string & stored_token,
const std::string & anchor_dir )

Join a stored token to a directory anchor using lexical normalization.

No file access, symlink resolution or existence check. The result is absolute only if input syntax or a suitable absolute anchor makes it so. Windows encoding/allocation errors can throw.

Parameters
[in]stored_tokenBorrowed path bytes; empty returns empty. Leading slash, alphabetic drive-colon or UNC syntax is considered already absolute.
[in]anchor_dirBorrowed directory anchor; empty leaves a normalized relative token rather than making it absolute.
Returns
Owned generic slash-form path bytes. Relative tokens are lexically normalized after joining; already absolute tokens only receive separator/path formatting.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ resultHdf5Mutex()

std::recursive_mutex & openswmm::io::resultHdf5Mutex ( )
inline

Access the shared recursive lock for result-file HDF5 operations.

Returns
Borrowed process-lifetime mutex shared by mesh output and source history writers. The caller owns each lock acquisition and must release it.
Note
Recursion permits mesh publication to call the source-history writer. The function returns the mutex without acquiring it.
Here is the caller graph for this function:

◆ utf8_path() [1/2]

std::filesystem::path openswmm::io::utf8_path ( const std::string & utf8)
inline

Convert borrowed path bytes into an owned native filesystem path.

Windows conversion uses char8_t UTF-8 construction. Allocation/encoding exceptions propagate; POSIX input may contain non-UTF-8 bytes.

Parameters
[in]utf8Path bytes: interpreted as UTF-8 on Windows, passed through unchanged on POSIX.
Returns
Owned filesystem path; no file lookup, normalization or open is performed.
Here is the caller graph for this function:

◆ utf8_path() [2/2]

template<class P>
requires std::same_as<std::remove_cvref_t<P>, std::filesystem::path>
std::filesystem::path openswmm::io::utf8_path ( P && )
delete

Passing an fs::path to utf8_path() is always a mistake — refuse it at compile time, on EVERY platform.

The value is already a path; re-encoding it is at best a no-op and at worst the very corruption this header exists to prevent. The reason this needs a deleted overload rather than a code review is that the mistake COMPILES ON POSIX: fs::path::string_type is std::string there, so path converts implicitly to the const std::string& parameter. On Windows string_type is std::wstring, no such conversion exists, and it is a hard error — so a Linux/macOS build and a local -fsyntax-only check both pass and only the MSVC job fails. That cost two Windows CI cycles (b3b1590d → b814bcf8, then again at 92e63366) before this guard existed.

Constrained to match ONLY an actual path: a bare overload taking const fs::path& would make utf8_path("literal") and utf8_path(char_ptr) ambiguous, since converting const char* to std::string and to path are equally good user-defined conversions. A template that matches path exactly wins against the conversion to std::string and loses for everything else, which is precisely the rule we want.