Vector storage private C reference
These registry, allocation, creation and destruction helpers are private to RBC. They are not substitutes for installed public stub entries. See Vector C API and storage primitives for their relationships and callback restrictions.
- group Vector storage private implementation
Registry and storage primitives with guarded callback boundaries.
Functions
-
static double MakeNaN(void)
Construct the quiet NaN stored during vector initialization.
The default path sets the IEEE binary64 bits; Borland constructs the word pair directly and Microsoft uses the C math library. No vector storage is allocated.
-
static size_t VectorElementSize(Rbc_VectorType type)
Return the byte stride for one real or complex value.
Uses sizeof(double) or sizeof(Rbc_Complex). Unsupported internal types panic; this is not a recoverable public type validator.
- Parameters:
type – [in] Validated real or complex storage type.
- Returns:
Byte stride of one value; unsupported types panic.
-
static int GetVectorByteCount(Tcl_Interp *interp, Rbc_VectorType type, Tcl_Size count, size_t *byteCountPtr)
Validate a value count and convert it to an allocation byte count.
Rejects negative counts and multiplication overflow with a Tcl error. Writes the output only on success; calls VectorElementSize, so the type must already be valid. Does not allocate storage or evaluate Tcl.
- Parameters:
interp – [in] See Interpreter arguments.
type – [in] Validated numeric storage type.
count – [in] Nonnegative number of values, not bytes.
byteCountPtr – [out] Required byte-count output; unchanged on failure.
- Returns:
TCL_OK on success; TCL_ERROR with a size diagnostic otherwise.
-
static int VectorAlive(VectorObject *vPtr)
Check logical liveness of a retained vector record.
The caller must already protect storage lifetime; this cannot validate an arbitrary pointer. Rejects destruction or interpreter deletion with RBC VECTOR DESTROYED. Does not check writability, name identity or numeric storage stability.
- Parameters:
vPtr – [in] Valid retained record whose logical liveness is checked; its interpreter must also remain allocated.
- Returns:
TCL_OK if live; TCL_ERROR with RBC VECTOR DESTROYED otherwise.
-
static void ReleaseVectorStorage(Tcl_Interp *interp, void *data, Tcl_FreeProc *freeProc)
Release detached numeric storage according to its ownership policy.
NULL storage and TCL_STATIC require no action; TCL_DYNAMIC uses ckfree. A custom release callback runs with the outer interpreter state saved and restored. The caller must install the completed replacement contract before calling, and separately protect record/interpreter lifetime across arbitrary callback code.
- Parameters:
interp – [in] See Interpreter arguments. Caller protects its lifetime across a custom destructor.
data – [in] Detached allocation to release, or NULL.
freeProc – [in] TCL_STATIC, TCL_DYNAMIC, or a callable custom destructor. TCL_VOLATILE must already have been converted to owned storage.
-
static void PublishVectorChange(VectorObject *vPtr, int all, Tcl_Size first, Tcl_Size last)
Publish an update while retaining the original vector identity.
Preserves vector and interpreter, saves interpreter state, optionally flushes mapped-array cache, then rechecks liveness before notifying all data or an inclusive interval. Callbacks may delete or replace the vector; this never resolves a replacement by name. Restores state and releases both records before returning.
- Parameters:
vPtr – [inout] Valid borrowed record; retained internally across publication callbacks.
all – [in] Nonzero publishes a full update; zero selects the interval.
first – [in] Inclusive first storage index; ignored for a full update.
last – [in] Inclusive last storage index; ignored for a full update.
-
static int CheckResizedVector(VectorObject *vPtr, void *data, Tcl_Size length, Tcl_Size size)
Validate a writable resize destination after callback activity.
Requires a retained record. Checks liveness and read-only state, then compares data pointer, length, capacity and full-vector selection against the caller snapshot. Reports RBC VECTOR CHANGED on layout mismatch. Does not prove that numeric values remained unchanged or that no same-layout mutation occurred.
- Parameters:
vPtr – [in] Retained destination to revalidate after callbacks.
data – [in] Expected current storage address; compared without dereferencing.
length – [in] Expected used length and full-selection extent.
size – [in] Expected capacity in values.
- Returns:
TCL_OK if writable and matching the snapshot; TCL_ERROR otherwise.
-
static char *VectorTraceError(Tcl_Obj *objPtr)
Retain a Tcl object as a variable-trace error result.
Increments the supplied object reference and returns it through the legacy char pointer signature. Valid only with traces registered using TCL_TRACE_RESULT_OBJECT, which tells Tcl to consume an object rather than interpret the pointer as message bytes.
- Parameters:
objPtr – [in] Non-NULL error object; this helper adds the reference consumed by Tcl trace processing.
- Returns:
The retained object cast to char *, for TCL_TRACE_RESULT_OBJECT only.
-
static void ZeroVectorElements(Rbc_VectorType type, VectorData data, Tcl_Size first, Tcl_Size last)
Zero the half-open interval [first,last) of typed storage.
Zeros both components for complex values. Bounds and capacity are caller preconditions; does not allocate, change metadata, invalidate extrema or notify.
- Parameters:
type – [in] Real or complex storage type.
data – [in] Borrowed writable typed buffer; must cover the requested interval.
first – [in] First storage index, inclusive; bounds are caller-validated.
last – [in] End storage index, exclusive; must not exceed capacity.
-
int Rbc_VectorInit(Tcl_Interp *interp)
Register the vector ensemble and standalone simplifier.
Initializes the shared NaN value and obtains interpreter-local registry data. Creates rbc::vector, ensures its command namespace exists, then registers rbc::vector::simplify. Returns TCL_ERROR if namespace creation fails, otherwise TCL_OK. Registration is not transactional: an already installed ensemble is not removed on that error. Registry cleanup belongs to the interpreter associated-data delete procedure.
- Parameters:
interp – [in] Owning interpreter receiving the ensemble and simplifier commands; see Interpreter arguments.
- Returns:
TCL_OK after registration, or TCL_ERROR on namespace-creation failure; earlier registration remains.
-
static void VectorRenameTrace(ClientData clientData, Tcl_Interp *interp, const char *oldName, const char *newName, int flags)
Record deletion during a command rename transaction.
clientData points to a live caller-owned flag, set only for TCL_TRACE_DELETE. Ignores name strings and never dereferences the vector, which user command traces may already have destroyed.
- Parameters:
clientData – [inout] Caller-owned int flag, valid until the temporary trace is removed; set on deletion.
interp – [in] Trace interpreter, unused here. See Interpreter arguments.
oldName – [in] Borrowed old command name, unused here.
newName – [in] Borrowed new name, possibly NULL for deletion; unused here.
flags – [in] Trace-event mask; only TCL_TRACE_DELETE changes the flag.
-
static int VectorRenameObjCmd(ClientData clientData, Tcl_Interp *interp, Tcl_Size objc, Tcl_Obj *const objv[])
Rename vector identity and its command without copying storage.
Resolves a literal source name and an existing destination namespace, validates the destination tail, and rejects registry or command collisions. A canonical unchanged name succeeds immediately. If an instance command exists, invokes global ::rename with a temporary command trace to detect deletion and recursive rename, then verifies the surviving command name. Rechecks registry collision before moving the hash entry. Retains the same vector, storage, clients and mapped-array association; the array name is not changed. Returns the qualified destination name. User trace effects and an already completed command rename are not rolled back if a later check fails.
See also
- Parameters:
clientData – [in] Borrowed interpreter-owned VectorInterpData registry, valid throughout the call.
interp – [in] Owning interpreter; see Interpreter arguments.
objc – [in] Argument count; the dispatcher checks ensemble-handler arity, while standalone simplify checks its own.
objv – [in] Borrowed array. Full ensemble arguments; literal old and new names at indices 2 and 3.
- Returns:
TCL_OK with the qualified new name, otherwise TCL_ERROR; trace side effects are not undone.
-
static long double SimplifyDistance(double ax, double ay, double bx, double by, double px, double py)
Measure distance from a finite point to a closed segment.
Uses long-double differences, scaled projection and hypot rather than squaring raw coordinates. If initial differences overflow, halves operands before subtraction and restores the factor afterward. Handles coincident endpoints and projections beyond either endpoint. Returns nonnegative distance; a distance outside the platform long-double range may be infinite. Callers validate finite input coordinates.
- Parameters:
ax – [in] Finite first segment endpoint X coordinate.
ay – [in] Finite first segment endpoint Y coordinate.
bx – [in] Finite second segment endpoint X coordinate.
by – [in] Finite second segment endpoint Y coordinate.
px – [in] Finite query point X coordinate.
py – [in] Finite query point Y coordinate.
- Returns:
Nonnegative point-to-segment distance; may overflow the platform long-double range.
-
static void SimplifyDeleted(Tcl_Interp *interp, ClientData clientData, Rbc_VectorNotify notify)
Invalidate a temporary destination ID on vector destruction.
clientData addresses a live caller-owned ID slot. Destruction clears the slot before the server frees remaining client records; update notifications leave it unchanged. Does not free the ID itself or access a destroyed vector.
- Parameters:
interp – [in] Owning notification interpreter, unused here. See Interpreter arguments.
clientData – [inout] Caller-owned Rbc_VectorId slot, valid for the observer’s lifetime.
notify – [in] Notification kind; DESTROY clears the slot without freeing the server-owned client record.
-
static void SimplifyFlush(Rbc_VectorId *idPtr)
Refresh a simplified destination mapped array after commit.
Uses a temporary observer ID whose deletion callback clears the caller slot. Copies the array name before unsetting and re-fetches the server after unset and sentinel write, restoring the trace only while the server survives with the same name. Skips absent IDs, disabled flushing and unmapped vectors. Trace side effects are not rolled back.
- Parameters:
idPtr – [inout] Required caller-owned observer-ID slot, possibly containing NULL; destruction callbacks clear it.
-
static int VectorSimplifyObjCmd(ClientData clientData, Tcl_Interp *interp, Tcl_Size objc, Tcl_Obj *const objv[])
Simplify paired whole real vectors with staged output storage.
Requires finite coordinates, finite nonnegative tolerance, equal input lengths and distinct writable existing destinations. Inputs may alias outputs. Iterative closed-segment Douglas-Peucker subdivision computes both outputs before mutation. Validation/allocation failures leave destinations unchanged. Commit installs both arrays before releasing old storage, flushing arrays or notifying observers. Temporary IDs track destination deletion during callbacks. Preserves identity and offsets, returns retained count, and does not roll back post-commit callback side effects.
See also
- Parameters:
clientData – [in] Borrowed interpreter-owned VectorInterpData registry, valid throughout the call.
interp – [in] Owning interpreter; see Interpreter arguments.
objc – [in] Argument count; the dispatcher checks ensemble-handler arity, while standalone simplify checks its own.
objv – [in] Borrowed array. Six standalone arguments: command, x, y, destX, destY, tolerance.
- Returns:
TCL_OK with the retained point count, otherwise TCL_ERROR before successful completion.
-
static int VectorSimplifyOp(ClientData clientData, Tcl_Interp *interp, Tcl_Size objc, Tcl_Obj *const objv[])
Adapt ensemble syntax to the standalone simplify command.
Borrows arguments and removes the ensemble command word by shifting the vector and count. The shared implementation performs arity checking, validation, allocation and commit; no Tcl arguments or vectors are copied by this adapter.
See also
- Parameters:
clientData – [in] Borrowed interpreter-owned VectorInterpData registry, valid throughout the call.
interp – [in] Owning interpreter; see Interpreter arguments.
objc – [in] Argument count; the dispatcher checks ensemble-handler arity, while standalone simplify checks its own.
objv – [in] Borrowed array. Seven full ensemble arguments; forwards objv+1 and objc-1 to the standalone handler.
- Returns:
The standalone simplifier status without additional copying or cleanup.
-
static int VectorObjCmd(ClientData clientData, Tcl_Interp *interp, Tcl_Size objc, Tcl_Obj *const objv[])
Validate and dispatch the vector ensemble operation.
Uses the typed command table to check name and arity before calling the selected handler. Borrows interpreter data and arguments, returning the handler status. Does not itself create vectors or implement transaction rollback.
See also
- Parameters:
clientData – [in] Borrowed interpreter-owned VectorInterpData registry, valid throughout the call.
interp – [in] Owning interpreter; see Interpreter arguments.
objc – [in] Argument count; the dispatcher checks ensemble-handler arity, while standalone simplify checks its own.
objv – [in] Borrowed array. Full ensemble arguments: command at index 0, operation at index 1.
- Returns:
The selected handler status, or TCL_ERROR for operation/arity failure.
-
static Tcl_Size ParseBool(void *clientData, Tcl_Interp *interp, Tcl_Size objc, Tcl_Obj *const objv[], void *dstPtr)
Consume one boolean creation-option argument.
Returns one consumed argument or minus one with a diagnostic. Uses the borrowed clientData option name for a missing-value error. Writes the destination integer only after successful conversion; does not retain the Tcl object.
- Parameters:
clientData – [in] Borrowed NUL-terminated option-name string used for missing-value diagnostics.
interp – [in] Diagnostic interpreter; see Interpreter arguments.
objc – [in] Number of remaining option-value arguments.
objv – [in] Borrowed value slice, with the option value at index zero.
dstPtr – [out] Required int receiving the converted boolean, changed only on success.
- Returns:
One consumed value, or -1 on error; this is not a Tcl status code.
-
static Tcl_Size ParseVectorLength(void *clientData, Tcl_Interp *interp, Tcl_Size objc, Tcl_Obj *const objv[], void *dstPtr)
Consume one Tcl_Size creation-option argument.
Returns one on success or minus one on missing/invalid input. Writes only after conversion. This parses a size integer, not the full vector length policy; caller checks allowed ranges and allocation limits.
- Parameters:
clientData – [in] Borrowed NUL-terminated option-name string used for missing-value diagnostics.
interp – [in] Diagnostic interpreter; see Interpreter arguments.
objc – [in] Number of remaining option-value arguments.
objv – [in] Borrowed value slice, with the option value at index zero.
dstPtr – [out] Required Tcl_Size receiving the parsed integer, changed only on success.
- Returns:
One consumed value, or -1 on error; this is not a Tcl status code.
-
static int GetSizeFromString(Tcl_Interp *interp, const char *string, Tcl_Size *valuePtr)
Convert a NUL-terminated string to Tcl_Size.
Owns a temporary retained Tcl object for conversion and releases it on either outcome. Returns the conversion status; does not evaluate an expression or validate vector-specific length limits.
- Parameters:
interp – [in] Diagnostic interpreter; see Interpreter arguments.
string – [in] Borrowed NUL-terminated integer spelling, copied into a temporary Tcl object.
valuePtr – [out] Required Tcl_Size output; consume only on successful conversion.
- Returns:
TCL_OK or TCL_ERROR from Tcl integer conversion.
-
static Tcl_Size ParseVectorType(void *clientData, Tcl_Interp *interp, Tcl_Size objc, Tcl_Obj *const objv[], void *dstPtr)
Consume an explicit real or complex creation type.
Accepts exact lowercase names only. On success stores type and marks specified, distinguishing explicit selection from the caller default. Returns one consumed argument, or minus one without changing option state on error.
- Parameters:
clientData – [in] Borrowed NUL-terminated option-name string used for missing-value diagnostics.
interp – [in] Diagnostic interpreter; see Interpreter arguments.
objc – [in] Number of remaining option-value arguments.
objv – [in] Borrowed value slice, with the option value at index zero.
dstPtr – [out] Required VectorTypeOption receiving the type and specified flag, changed only on success.
- Returns:
One consumed value, or -1 on error; this is not a Tcl status code.
-
static int VectorCreateObjCmd(ClientData clientData, Tcl_Interp *interp, Tcl_Size objc, Tcl_Obj *const objv[])
Parse vector creation options and process names sequentially.
Borrows ensemble arguments and owns the parsed name array, work string and result object. Prechecks existing candidate vectors for read-only state before processing names. Exact registered names take precedence over legacy numeric size/range suffixes; -literal disables suffix interpretation. Explicit type changes are rejected. Real names without parentheses receive default array mappings; complex or parenthesized names do not. Positive requested lengths resize storage; zero does not truncate an existing vector. Retains each returned vector and interpreter across resize and publication, checks liveness, and returns the last qualified name. Later failures do not roll back earlier creations, reconfiguration or callback effects.
See also
- Parameters:
clientData – [in] Borrowed interpreter-owned VectorInterpData registry, valid throughout the call.
interp – [in] Owning interpreter; see Interpreter arguments.
objc – [in] Argument count; the dispatcher checks ensemble-handler arity, while standalone simplify checks its own.
objv – [in] Borrowed array. Full ensemble arguments; names and creation options start at index 2.
- Returns:
TCL_OK with the final qualified name, otherwise TCL_ERROR; earlier creations remain.
-
static int VectorDestroyObjCmd(ClientData clientData, Tcl_Interp *interp, Tcl_Size objc, Tcl_Obj *const objv[])
Destroy named vectors in argument order.
Uses the range-aware lookup helper, then destroys the entire returned vector, not only its selected interval. Stops on the first lookup error; earlier destruction and observer side effects remain. No names is a successful no-op. Read-only state protects data mutation, not destruction. Lookup and destruction may run callbacks; this handler does not stage or retain all targets in advance.
See also
- Parameters:
clientData – [in] Borrowed interpreter-owned VectorInterpData registry, valid throughout the call.
interp – [in] Owning interpreter; see Interpreter arguments.
objc – [in] Argument count; the dispatcher checks ensemble-handler arity, while standalone simplify checks its own.
objv – [in] Borrowed array. Full ensemble arguments; references to destroy start at index 2.
- Returns:
TCL_OK after all requested destructions, otherwise TCL_ERROR; earlier destructions remain.
-
static int VectorExprObjCmd(ClientData clientData, Tcl_Interp *interp, Tcl_Size objc, Tcl_Obj *const objv[])
Evaluate an expression as Tcl values or a newly named vector.
Without -name delegates directly to Rbc_ExprVector. Named output resolves an existing destination namespace and rejects vector or command collisions before evaluation and again afterward. Evaluates once into an owned temporary, creates an unmapped vector of the resulting type, and transfers its storage without Tcl-list conversion. A final
#autocomponent requests generated naming. Returns the qualified new name; never overwrites an existing vector. Frees the temporary and work strings on every exit. Expression callback side effects are not rolled back.- Parameters:
clientData – [in] Unused ensemble registry pointer; the handler obtains registry data from interp.
interp – [in] Owning evaluation interpreter; see Interpreter arguments.
objc – [in] Three for list output, or five for named output; other counts are rejected.
objv – [in] Full ensemble array: expression at index 2, or -name, name, expression at indices 2 through 4.
- Returns:
TCL_OK with copied values or the new qualified name, otherwise TCL_ERROR; evaluation side effects remain.
-
static int VectorNamesObjCmd(ClientData clientData, Tcl_Interp *interp, Tcl_Size objc, Tcl_Obj *const objv[])
List registered vector names with an optional glob filter.
Walks the interpreter vector hash table, appending fully qualified keys to a new Tcl list. Matching uses Tcl_StringMatch on the full name. Order follows hash traversal and is not sorted. Does not enumerate Tcl aliases, instance command spellings or mapped arrays, and does not invoke vector observers.
See also
- Parameters:
clientData – [in] Borrowed interpreter-owned VectorInterpData registry, valid throughout the call.
interp – [in] Owning interpreter; see Interpreter arguments.
objc – [in] Argument count; the dispatcher checks ensemble-handler arity, while standalone simplify checks its own.
objv – [in] Borrowed array. Full ensemble arguments; optional glob pattern at index 2.
- Returns:
TCL_OK with a list of qualified registry names in hash traversal order.
-
VectorInterpData *Rbc_VectorGetInterpData(Tcl_Interp *interp)
Obtain or lazily initialize an interpreter-local vector registry.
Returns borrowed associated data. First access allocates the vector, math and special-index tables, installs built-in functions and registers interpreter cleanup. Does not create Tcl commands or establish thread-shared storage.
- Parameters:
interp – [in] See Interpreter arguments. Owns the lazily allocated registry.
- Returns:
Borrowed interpreter-associated registry; no ownership transfer.
-
static void VectorInterpDeleteProc(ClientData clientData, Tcl_Interp *interp)
Destroy registered vectors and release interpreter-local tables.
Repeatedly takes the first remaining registry entry because destruction mutates the table and invokes callbacks. Deletes the math/index table containers and associated data, then frees the registry record. This is interpreter teardown, not a general-purpose registry reset API.
- Parameters:
clientData – [in] Owned VectorInterpData associated with the interpreter; released here.
interp – [in] See Interpreter arguments. Interpreter undergoing teardown.
-
VectorObject *Rbc_VectorNew(VectorInterpData *dataPtr)
Allocate an unregistered empty real vector record.
Initializes static NULL storage, zero length/capacity, an empty observer chain, idle notifications, invalid extrema and no array flushing. The caller owns the record and may register it or use it as a temporary; release with Rbc_VectorFree. Does not create a name, Tcl command, mapped array or numeric allocation.
- Parameters:
dataPtr – [in] Borrowed owning-interpreter registry; must outlive the new record.
- Returns:
Owned empty record, released with Rbc_VectorFree.
-
VectorObject *Rbc_VectorCreate(VectorInterpData *dataPtr, const char *vecName, const char *cmdName, const char *varName, Rbc_VectorType type, int *newPtr)
Create or reuse a registered vector and configure its access surfaces.
Qualifies the name in the current namespace; #auto selects an unused registry and command name. Existing vectors must be writable and have the requested type. Checks command collisions, replaces an existing instance command, and optionally maps an array. NULL command/variable arguments suppress that setup. Returns a borrowed record and writes newPtr on success, or NULL on error. Failure frees a newly created record, but does not roll back existing-object changes. Retains the record and interpreter across command deletion and mapping, and rejects destruction, new protection or replacement commands before continuing.
- Parameters:
dataPtr – [in] Borrowed registry receiving or reusing the identity.
vecName – [in] Borrowed requested name; #auto tail generates an unused name.
cmdName – [in] Borrowed instance command name, or NULL to omit command setup.
varName – [in] Borrowed array mapping name; NULL omits setup and empty requests unmapping.
type – [in] Requested real/complex type; an existing identity must match.
newPtr – [out] Required output: nonzero for a new identity, zero for reuse, written only on success.
- Returns:
Borrowed registered identity on success, or NULL with a diagnostic.
-
static void VectorInstDeleteProc(ClientData clientData)
Destroy a vector when its instance command is deleted.
Clears the command token before calling Rbc_VectorFree, avoiding deletion of the same command again. Called by Tcl; no record access follows destruction.
- Parameters:
clientData – [inout] Vector record owned by the deleted instance command; cleared command token prevents recursive deletion.
-
static void FreeVectorRecord(DestroyData data)
Release a record after Tcl preservation references have drained.
Calls ckfree on the supplied allocation. Used for deferred vector and client record reclamation; resources must already have been detached.
- Parameters:
data – [in] Owned vector or client record whose resources are already detached; freed here.
-
void Rbc_VectorFree(VectorObject *vPtr)
Destroy a vector identity, its observers and owned resources.
Ignores recursive destruction while the retained record is marked destroying. Preserves record/interpreter, deletes the command and mapping, unregisters the name, cancels pending idle work and delivers synchronous DESTROY with length zero. A temporary name copy remains valid during observer delivery. Detaches remaining clients, releases non-static storage, then defers record reclamation. Callbacks can run during command deletion, unmapping, notification and custom storage release. Preservation delays record reclamation, not logical destruction or storage cleanup. Requires a live non-NULL record; ignores read-only state.
- Parameters:
vPtr – [in] Valid non-NULL identity to destroy; may already be marked destroying during recursive cleanup.
-
int Rbc_VectorDuplicate(VectorObject *destPtr, VectorObject *srcPtr)
Resize an existing destination and copy the selected source values.
Requires matching numeric types; selected length is last-first+1. Checks byte arithmetic and writability, copies with memmove and copies the source offset. Completes copying before releasing old storage, including same-object slices. Invalidates extrema but does not create a vector, flush or notify. Retains the destination through custom release and rejects destruction, protection or storage/selection changes before returning success. Callback effects remain.
- Parameters:
destPtr – [inout] Live writable same-type destination; may equal the source.
srcPtr – [in] Live source with a valid inclusive first/last selection; values are copied, not adopted.
- Returns:
TCL_OK on successful copy and post-callback checks; TCL_ERROR otherwise.
-
static int ResetVectorStorage(VectorObject *vPtr, void *valueArr, Tcl_Size length, Tcl_Size size, Tcl_FreeProc *freeProc)
Validate and replace the complete storage ownership contract.
Checks writability, nonnegative length/capacity, length<=capacity and byte counts. NULL data or zero capacity installs empty static storage. TCL_VOLATILE copies used values into capacity-sized owned storage, even for the same input address. Otherwise adopts/borrows the supplied pointer under freeProc. Releases the old owned allocation only when its address differs, after installing the completed metadata. Retains the record and interpreter through release and publication, skipping publication after destruction. Returns TCL_OK once the buffer ownership contract is accepted, even if callbacks destroy the vector; callers must not free an adopted buffer again. Precommit errors leave ownership with the caller. Does not reset the shared first/last selection.
- Parameters:
vPtr – [inout] Live writable destination; its current numeric type selects the element size.
valueArr – [in] Buffer to copy, borrow or adopt; NULL selects empty storage.
length – [in] Nonnegative used count, at most size.
size – [in] Nonnegative capacity in values; zero selects empty storage.
freeProc – [in] TCL_STATIC borrows, TCL_DYNAMIC adopts, TCL_VOLATILE copies, or a custom release callback. Ownership is accepted only on success.
- Returns:
TCL_OK once the storage contract is accepted, even if later callbacks destroy the vector; TCL_ERROR before acceptance.
-
int Rbc_VectorReset(VectorObject *vPtr, double *valueArr, Tcl_Size length, Tcl_Size size, Tcl_FreeProc *freeProc)
Apply a real storage reset after checking the vector type.
Rejects a complex vector with a Tcl error; otherwise delegates to ResetVectorStorage, including its ownership and callback restrictions. Does not convert types or make a separate numeric result.
- Parameters:
vPtr – [inout] Live real destination; complex type is rejected.
valueArr – [in] Real buffer under the freeProc ownership policy, or NULL.
length – [in] Nonnegative used count, at most size.
size – [in] Nonnegative capacity in doubles, not bytes.
freeProc – [in] Storage policy passed to the shared reset implementation.
- Returns:
Tcl status with the shared reset ownership-acceptance semantics.
-
static void VectorNotifyClients(ClientData clientData)
Deliver a snapshot of vector observers with stable update metadata.
Preserves vector, interpreter and snapshotted client IDs, not chain links. Clears pending update state before invoking callbacks. New clients wait for a later notification; detached or reassigned IDs are skipped and destruction stops remaining update callbacks. Temporarily installs the event interval on each client and restores its outer interval after nested delivery. Releases every retained ID even when delivery stops early.
- Parameters:
clientData – [in] Valid VectorObject for this delivery, including destruction delivery; retained internally, but not owned by the callback.
-
int Rbc_VectorChangeLength(VectorObject *vPtr, Tcl_Size length)
Resize typed storage without publishing a change to clients.
Checks writability and a nonnegative length. Chooses a capacity starting at DEF_ARRAY_SIZE and doubling to fit, with overflow protection. Reuses an equal capacity allocation; otherwise copies the retained prefix into new storage. Zeros added values and installs length/capacity, selection 0..length-1 and invalid extrema before releasing old owned storage. Zero length releases storage. Does not flush or notify. Retains the record and interpreter across custom release; returns TCL_ERROR if it destroys, protects or changes the installed storage/selection. Such errors do not roll back the commit or callback effects.
- Parameters:
vPtr – [inout] Live writable destination; its selection and extrema metadata are updated.
length – [in] Nonnegative requested used count in values, subject to allocation limits.
- Returns:
TCL_OK on success; TCL_ERROR for protection, size or post-callback failures.
-
int Rbc_VectorLookupName(VectorInterpData *dataPtr, const char *vecName, VectorObject **vPtrPtr)
Resolve a complete vector reference including an optional selection.
Delegates to Rbc_VectorParseElement with current/global namespace search and rejects trailing unconsumed characters. Returns TCL_OK and writes a borrowed vector pointer only on success, otherwise TCL_ERROR with an interpreter diagnostic. Parsing may update the selection and evaluate index expressions; this is not a literal-name lookup or a lifetime-retaining API. Callers needing to survive subsequent callbacks must retain and revalidate the object separately.
See also
Rbc_VectorParseElement
- Parameters:
dataPtr – [in] Live owning registry; its interpreter receives lookup diagnostics.
vecName – [in] NUL-terminated complete reference, including any parenthesized selection.
vPtrPtr – [out] Required borrowed-vector output, written only on success.
- Returns:
TCL_OK on complete consumption, otherwise TCL_ERROR.
-
static int GetVectorIndexFromSpan(Tcl_Interp *interp, VectorObject *vPtr, const char *start, const char *end, Tcl_Size *indexPtr, int flags)
Parse an index from a bounded string span.
Requires start and end in one readable buffer with end not before start. Copies the half-open span into a temporary retained Tcl object, delegates index and flag semantics to Rbc_VectorGetIndex, then releases the object. Does not require a NUL byte at end.
See also
Rbc_VectorGetIndex
- Parameters:
interp – [in] Optional diagnostic interpreter; see Interpreter arguments.
vPtr – [inout] Live vector supplying index context; evaluation can run Tcl callbacks.
start – [in] First byte of the readable index span.
end – [in] One-past-last byte in the same buffer, at or after start.
indexPtr – [out] Required output, written only after successful parsing.
flags – [in] Index flags forwarded to Rbc_VectorGetIndex.
- Returns:
TCL_OK or TCL_ERROR from index parsing; registered special indices are not enabled.
-
static void ScheduleVectorUpdate(VectorObject *vPtr, int all, Tcl_Size first, Tcl_Size last)
Coalesce changed intervals and apply the notification policy.
Destroyed vectors are ignored. Increments dirty even when notifications are disabled. A full update supersedes interval metadata; ranged updates merge inclusive endpoints. Immediate mode can invoke callbacks before return; idle mode queues at most one pending callback. Does not itself invalidate or recompute extrema.
- Parameters:
vPtr – [inout] Valid vector record; logically destroyed records are ignored.
all – [in] Nonzero supersedes ranged metadata with a full update.
first – [in] Validated inclusive first changed storage index; ignored when all is nonzero.
last – [in] Validated inclusive last changed storage index; ignored when all is nonzero.
-
static void InvalidateVectorRange(VectorObject *vPtr)
Mark cached extrema as requiring recomputation.
Stores NaN bounds and negative indices, then sets UPDATE_RANGE. Does not inspect numeric data, increment dirty or schedule observers; callers separately publish the change.
- Parameters:
vPtr – [inout] Valid record whose extrema cache is invalidated; storage is not examined.
-
static int UpdateVectorRangeForChangedRange(VectorObject *vPtr, Tcl_Size first, Tcl_Size last)
Maintain exact real-vector extrema after a bounded modification.
Requires a real vector whose caller has already changed only the stated inclusive interval. Returns FALSE without committing when the cache is invalid, bounds are invalid, an old extremum was touched or cache state is inconsistent. Otherwise scans only changed finite values, retaining the earliest index on equal extrema, and commits the exact cache. TRUE also covers a vector with no finite values.
- Parameters:
vPtr – [inout] Valid real vector with completed in-place writes and existing cache metadata.
first – [in] First changed storage index, inclusive.
last – [in] Last changed storage index, inclusive; invalid intervals cannot update the cache incrementally.
- Returns:
Nonzero if the extrema cache was updated; zero requests full recomputation later.
-
static char *VectorVarTraceImpl(ClientData clientData, Tcl_Interp *interp, char *part1, char *part2, int flags)
Perform one mapped-array access while the wrapper retains its owners.
Reads materialize copied values; writes stage conversion before committing an inclusive interval; unsets compact storage and publish a full update. Value and index expressions may execute Tcl. Revalidate liveness, writability and storage layout before writing, and retain a private conversion object so callback changes to the array cannot invalidate a complex pair. Callback effects are not rolled back. Errors are retained Tcl objects for traces registered with TCL_TRACE_RESULT_OBJECT.
- Parameters:
clientData – [inout] Borrowed traced vector record; the wrapper preserves its allocation, not destroyed numeric storage.
interp – [inout] Borrowed interpreter for lookup, evaluation and diagnostics; caller keeps it valid throughout the call.
part1 – [in] Borrowed array variable name supplied by Tcl for this trace invocation.
part2 – [in] Borrowed element index text, or NULL for a whole-array operation.
flags – [in] Tcl trace operation and namespace flags; error results follow TCL_TRACE_RESULT_OBJECT ownership.
-
static char *VectorVarTrace(ClientData clientData, Tcl_Interp *interp, char *part1, char *part2, int flags)
Retain the vector and interpreter for the complete variable trace.
Keeps the record alive across index/value expressions, array traces, custom index procedures, storage release and immediate observer notification. This does not retain destroyed numeric storage; the implementation checks state again before access after callbacks. Returns an owned trace-error object or NULL, releasing both preservation references on every exit.
- Parameters:
clientData – [inout] Borrowed traced vector record; the wrapper preserves its allocation, not destroyed numeric storage.
interp – [inout] Borrowed interpreter for lookup, evaluation and diagnostics; caller keeps it valid throughout the call.
part1 – [in] Borrowed array variable name supplied by Tcl for this trace invocation.
part2 – [in] Borrowed element index text, or NULL for a whole-array operation.
flags – [in] Tcl trace operation and namespace flags; error results follow TCL_TRACE_RESULT_OBJECT ownership.
-
static char *BuildQualifiedName(Tcl_Interp *interp, const char *name, Tcl_DString *fullName)
Build an absolute name relative to the current namespace.
NULL input returns NULL without initializing the output. Otherwise initializes the caller DString, preserves an already absolute spelling, or prefixes the current namespace. Returns borrowed DString storage that the caller must free. Does not create or validate namespace existence.
- Parameters:
interp – [inout] Borrowed interpreter for lookup, evaluation and diagnostics; caller keeps it valid throughout the call.
name – [in] Borrowed name, or NULL to return without initializing fullName.
fullName – [out] Caller-owned DString initialized for non-NULL name; caller frees it after using the returned buffer.
-
static int ParseQualifiedName(Tcl_Interp *interp, const char *qualName, Tcl_Namespace **nsPtrPtr, const char **namePtrPtr)
Split a name at its final namespace separator.
Without a separator, returns a NULL namespace and the original name. Otherwise resolves the namespace and returns a tail pointer into the borrowed input. Does not create namespaces, parse vector ranges or validate the tail. Output pointers are meaningful only on TCL_OK; a missing namespace returns TCL_ERROR without constructing a vector-specific diagnostic.
- Parameters:
interp – [inout] Borrowed interpreter for lookup, evaluation and diagnostics; caller keeps it valid throughout the call.
qualName – [in] Borrowed NUL-terminated name, possibly unqualified or empty.
nsPtrPtr – [out] Required borrowed namespace output on success; NULL denotes an unqualified name.
namePtrPtr – [out] Required tail output pointing into qualName on success; no string is allocated.
-
static char *GetQualifiedName(Tcl_Namespace *nsPtr, const char *name, Tcl_DString *resultPtr)
Join a known namespace and an unqualified tail.
Initializes the caller DString and returns its borrowed buffer, adding exactly the join separator for the global namespace. Requires a live namespace and readable tail; does not parse or normalize a qualified tail. Caller releases the DString.
- Parameters:
nsPtr – [in] Borrowed live namespace supplying its absolute fullName.
name – [in] Borrowed unqualified NUL-terminated tail; not parsed or normalized.
resultPtr – [out] Caller-owned DString initialized here; caller frees it after using the borrowed return buffer.
-
static VectorObject *GetVectorObject(VectorInterpData *dataPtr, const char *name, int flags)
Resolve a literal vector registry name with controlled namespace search.
Explicit namespace syntax restricts lookup to that namespace. Otherwise flags select current namespace first and optional global fallback. Returns a borrowed vector or NULL, without changing its index selection. Range syntax belongs to higher-level parsing, not this lookup helper.
- Parameters:
dataPtr – [in] Borrowed live per-interpreter vector registry; lookup does not transfer ownership.
name – [in] Borrowed literal registry name; no range suffix is parsed.
flags – [in] NS_SEARCH_CURRENT and NS_SEARCH_GLOBAL bits for unqualified lookup, in that order.
-
static VectorObject *FindVectorInNamespace(VectorInterpData *dataPtr, Tcl_Namespace *nsPtr, const char *vecName)
Find a literal vector in one namespace registry scope.
Builds a temporary qualified key, queries the interpreter-local vector table and frees the key. Returns a borrowed record or NULL. Does not resolve Tcl command aliases or acquire a vector client ID.
- Parameters:
dataPtr – [in] Live interpreter-local vector registry.
nsPtr – [in] Namespace used to qualify vecName.
vecName – [in] NUL-terminated literal name, without range parsing.
- Returns:
Borrowed registry record, or NULL if the qualified key does not exist.
-
static void DeleteCommand(VectorObject *vPtr)
Remove the instance command without recursively destroying its vector.
Clears the stored command token first, disables the vector command deletion callback and deletes by token rather than caller-relative name. Other command traces may still run. Caller owns record/interpreter lifetime across deletion; this helper does not remove the registry entry or mapped variable.
- Parameters:
vPtr – [inout] Vector whose instance command is detached and deleted; caller retains its lifetime.
-
static void UnmapVariable(VectorObject *vPtr)
Detach and unset the vector mapped-array access surface.
Captures the owned name and flags, clears arrayName before removing the RBC trace and unsetting the variable, then frees the captured name. User unset traces may destroy or remap the vector. No vector fields are accessed after unset; caller owns surrounding lifetime and continuation checks.
- Parameters:
vPtr – [inout] Vector whose owned array name is detached and released; caller retains its lifetime.
-
int Rbc_CreateVector2(Tcl_Interp *interp, const char *vecName, const char *cmdName, const char *varName, Tcl_Size initialSize, Rbc_VectorType type, Rbc_Vector **vecPtrPtr)
Create or reuse a typed vector with explicit command and array names.
Validates nonnegative initialSize and real/complex type, then delegates to Rbc_VectorCreate. A positive size resizes; zero leaves an existing vector length unchanged. Writes an optional borrowed output pointer on success. Returns a Tcl status; initial resize failure removes a newly created identity if still alive. The output pointer is untouched on failure. Retains and checks the identity across callbacks; does not explicitly publish the initial resize. Existing-object changes and callback effects are not rolled back.
- Parameters:
interp – [inout] Borrowed interpreter for lookup, evaluation and diagnostics; caller keeps it valid throughout the call.
vecName – [in] Borrowed registry name or
#autorequest, resolved by Rbc_VectorCreate.cmdName – [in] Borrowed command name, or NULL to omit command setup.
varName – [in] Borrowed array mapping name, or NULL to omit mapping setup; passed unchanged to Rbc_VectorCreate.
initialSize – [in] Nonnegative element count; zero leaves an existing length unchanged, positive values request resizing.
type – [in] RBC_VECTOR_REAL or RBC_VECTOR_COMPLEX; existing vectors must have the requested type.
vecPtrPtr – [out] Optional borrowed vector output, written only on success; no client retention token is created.
-
struct VectorTypeOption
Explicit vector creation type parsed before allocating storage.
Public Members
-
Rbc_VectorType type
Requested real or complex storage type.
-
int specified
Nonzero when the caller explicitly supplied a type option.
-
Rbc_VectorType type
-
static double MakeNaN(void)
Parameter and ownership conventions
Allocation, storage replacement and notification helpers use explicit parameter directions. A borrowed record may still be mutated; an input buffer may be adopted if the reset contract says so. Output arguments are not implicitly initialized on failure. The individual contract defines each case; see C calling conventions for the common terminology.
Data records and member contracts
These records describe stored state and resource ownership. Their presence in the reference does not make private layouts part of the installed C API.
-
struct VectorOpSpec
Typed command dispatch entry with shared argument validation metadata.
Public Members
-
Rbc_OpSpecHeader header
Operation name, total argument bounds and usage suffix.
-
RbcVectorOp *proc
Typed command handler for this operation.
-
Rbc_OpSpecHeader header
-
struct ParseInfo
Expression scan position and current token.
-
struct Rbc_VectorIdStruct
Observer token for a vector.
Detaching invalidates the token; notification snapshots defer reclamation during callbacks.
Public Members
-
unsigned int magic
Magic value designating whether this really is a vector token or not.
-
VectorObject *serverPtr
Borrowed vector; cleared when the ID is detached.
-
Rbc_VectorChangedProc *proc
Routine to call when the contents of the vector change or the vector is deleted.
-
ClientData clientData
Data passed whenever the vector change procedure is called.
-
Rbc_ChainLink *linkPtr
Used to quickly remove this entry from its server’s client chain.
-
int updateAll
Nonzero means the entire vector, or an unknown range, changed.
-
int updateRangeValid
Nonzero when updateFirst and updateLast specify a modified range.
-
Tcl_Size updateFirst
First changed source index, inclusive; meaningful only when updateRangeValid is set.
-
Tcl_Size updateLast
Last changed source index, inclusive; meaningful only when updateRangeValid is set.
-
unsigned int magic
-
struct Rbc_Vector_s
Vector storage and command state.
Named vectors belong to the interpreter registry; client tokens observe without preserving vector lifetime.
Public Members
-
Rbc_VectorType type
Real or complex storage discriminator; data must agree with it.
-
int readOnly
Protect values, length and index offset; not vector lifetime.
-
VectorData data
Storage allocation governed by freeProc; growth or reset can invalidate borrowed pointers.
-
Tcl_Size length
Current number of values in the array.
-
Tcl_Size size
Maximum number of values that can be stored in the value array.
-
double min
Minimum and maximum values in the vector.
-
double max
Minimum and maximum values in the vector.
-
Tcl_Size minIndex
Source index of cached finite minimum, or -1 when unavailable.
-
Tcl_Size maxIndex
Source index of cached finite maximum, or -1 when unavailable.
-
int dirty
Indicates if the vector has been updated.
-
char *name
The namespace-qualified name of the vector command.
It points to the hash key allocated for the entry in the vector hash table; destruction keeps a temporary copy while callbacks run after removing the registration.
-
VectorInterpData *dataPtr
Borrowed interpreter-associated vector registry.
-
Tcl_Interp *interp
Interpreter associated with the vector.
-
Tcl_HashEntry *hashPtr
If non-NULL, pointer in a hash table to track the vectors in use.
-
Tcl_FreeProc *freeProc
Address of procedure to call to release storage for the value array, Optionally can be one of the following: TCL_STATIC, TCL_DYNAMIC, or TCL_VOLATILE.
-
char *arrayName
The namespace-qualified name of the Tcl array variable mapped to the vector (allocated).
If NULL, indicates that the vector isn’t mapped to any variable
-
Tcl_Size offset
Offset from zero of the vector’s starting index.
-
Tcl_Command cmdToken
Token for vector’s Tcl command.
-
int destroying
Destruction started; reject recursive deletion and new clients.
-
int notifyFlags
Notification flags.
See definitions below
-
int varFlags
Indicate if the variable is global, namespace, or local.
-
int freeOnUnset
For backward compatibility only: If non-zero, free the vector when its variable is unset.
-
int flush
Nonzero flushes mapped-array cached entries when values change.
-
Tcl_Size first
Selected region of vector.
This is used mostly for the math routines
-
Tcl_Size last
Selected region of vector.
This is used mostly for the math routines
-
int updateAll
Nonzero means the entire vector, or an unknown range, changed.
-
int updateRangeValid
Nonzero when updateFirst and updateLast specify a modified range.
-
Tcl_Size updateFirst
First changed source index, inclusive; meaningful only when updateRangeValid is set.
-
Tcl_Size updateLast
Last changed source index, inclusive; meaningful only when updateRangeValid is set.
-
Rbc_VectorType type
-
struct Value
Temporary expression value owning its result vector.
Public Members
-
VectorObject *vPtr
Temporary result vector used by the expression parser.
-
VectorObject *vPtr
-
union VectorData
- #include <rbcVectorInt.h>
Typed views of one vector storage allocation; type is stored in the owning vector.
Public Members
-
double *real
Real-value view when the vector type is real.
-
Rbc_Complex *complex
Complex-value view when the vector type is complex.
-
void *raw
Untyped storage view used for allocation and release.
-
double *real
-
struct VectorInterpData
Interpreter-associated vector registry and expression/index dispatch tables.
Public Members
-
Tcl_HashTable vectorTable
Table of vectors.
-
Tcl_HashTable mathProcTable
Table of vector math functions.
-
Tcl_HashTable indexProcTable
Registered special-index callbacks indexed by name.
-
Tcl_Interp *interp
Borrowed owning interpreter.
-
unsigned int nextId
Next candidate suffix for automatic vector names.
-
Tcl_HashTable vectorTable