Author: Jan Nijtmans <[email protected]>
State: Draft
Type: Project
Tcl-Version: 9.1
Tcl-Branch: attemptgetstring
Abstract
This TIP proposes new functions Tcl_AttemptGetString() and Tcl_AttemptGetStringFromObj() and a few more Attempt functions. They do almost the same as the non-Attempt variant, only in case of failing memory allocation they return NULL (or -1) in stead of panicing.
Rationale
The new functions allow to handle memory exhaustion better than the old functions do.
The main place this new function will be used is in handling lists and dictionaries. When they become huge, causing memory exhaustion, it's better to clear its contents and give an error-message than panicing.
Demonstrating this, the test suite contains a testobj huge command, which creates a Tcl_Obj which will panic whenever its string representation is created. With this TIP (and when the Attempt functions are used in the command implementation) using this testobj huge will no longer panic but generate a proper error-message (without a memory-leak).
Demo:
% tcltest8.6
> testobj huge
panic .....
% tcltest9.0
> set x [testobj huge]
cannot allocate ???? bytes
> set x
cannot allocate ???? bytes
Specification
Declare and implement new functions:
char *Tcl_AttemptGetString(Tcl_Obj *objPtr)
char *Tcl_AttemptGetStringFromObj(Tcl_Obj *objPtr, Tcl_Size *lengthPtr)
char *Tcl_AttemptSetStringObj(Tcl_Obj *objPtr, const char *bytes, Tcl_Size length)
Tcl_UniChar *Tcl_AttemptGetUnicode(Tcl_Obj *objPtr)
Tcl_UniChar *Tcl_AttemptGetUnicodeFromObj(Tcl_Obj *objPtr, Tcl_Size *lengthPtr)
Tcl_UniChar *Tcl_AttemptSetUnicodeObj(Tcl_Obj *objPtr, const Tcl_UniChar *bytes, Tcl_Size length)
Tcl_Obj *Tcl_AttemptDuplicateObj(Tcl_Obj *objPtr)
These functions will return NULL on a memory errors.
- Tcl_Size Tcl_AttemptGetCharLength(Tcl_Obj *objPtr)
This function will return -1 on a memory errors.
The contract of the updateStringProc() changes. In Tcl 8.6 and 9.0, the updateStringProc() is expected to panic if an allocation error occurs (the Tcl_Alloc() call already does that). Tcl_Obj types which want to use the new feature, now can return NULL: The functions calling the updateStringProc will either do the panic (for the non-Attempt variant) or do proper cleanup and generate a runtime error.
Implementation
See the attemptgetstring branch.
Copyright
This document has been placed in the public domain.
