The majority of TEKlib's functionality is located in shared modules. The link libraries provide only functions that operate on elementary data structures (such as lists, hooks and taglists), and they allow the setup of applications and modules.
tek
-
Common functions for elementary datatypes and module setup,
usually linked to modules
tekc
-
Additionally provides teklib:TEKCreate()
. This library is linked
to applications that wish to embed TEKlib, but do not use
teklib:TEKMain()
as their application entrypoint.
tekcmain
-
Additionally resolves a platform-specific main()
and calls
teklib:TEKMain()
. This is the typical C/C++ language startup of a
freestanding TEKlib application.
tekmain
-
This library is based on tekc
and additionally defines an
entrypoint for applications on platforms on which TEKlib constitutes
the operating system. This is the case on the Playstation 2
architecture, for example.
teklib:TAddDate()
- Add number of days and a time to a date
teklib:TAddHead()
- Add a node at the head of a list
teklib:TAddTail()
- Add a node at the tail of a list
teklib:TAddTime()
- Add a time to another
teklib:TCallHookPkt()
- Invoke a hook
teklib:TCmpTime()
- Compare times
teklib:TCreateTime()
- Create a time from days, seconds, micros
teklib:TDestroy()
- Destroy a handle
teklib:TDestroyList()
- Unlink all nodes in a list and destroy them
teklib:TDiffDate()
- Calculate days and time difference between dates
teklib:TEKCreate()
- Create an initial TEKlib task/thread context
teklib:TEKMain()
- Entrypoint for a freestanding application
teklib:TExtractTime()
- Extract days, seconds, micros from a time
teklib:TFindHandle()
- Find a named handle in a list
teklib:TForEachTag()
- Traverse all key/value pairs in a tag list
teklib:TFreeInstance()
- Free a module instance
teklib:TGetTag()
- Get a value from a list of tagitems
teklib:TInitHook()
- Initialize a hook with a function and data
teklib:TInitInterface()
- Initialize an interface structure
teklib:TInitList()
- Initialize a list structure
teklib:TInitVectors()
- Initialize a module function table
teklib:TInsert()
- Insert a node into a list
teklib:TNewInstance()
- Create a module instance copy
teklib:TNodeUp()
- Move a node towards the head of its list
teklib:TRemHead()
- Remove a node from the head of a list
teklib:TRemove()
- Remove a node from whatever list it is linked to
teklib:TRemTail()
- Remove a node from the tail of a list
teklib:TSubDate()
- Subtract a number of days and a time from a date
teklib:TSubTime()
- Subtract a time from another
One of the most versatile data structures in TEKlib are arrays of key/value pairs. These pairs are called tags, hence the term tagitem for the resulting data structure, and taglist for an array composed of tagitems. Example:
struct TTagItem my_taglist[5] = { MY_Points, vertices, MY_NumPoints, (TTAG) 3, MY_Color, (TTAG) 0xff0000, MY_Name, "Red triangle", TTAG_DONE };
The TTAG
type has the guaranteed ability to carry pointers on all
architectures. This allows, in essence, to transport any kind of data
in tagitems. The tti_Tag
field can contain user codes or control
codes. User codes are identified by their combination with
TTAG_USER
, for example
#define MY_Points (TTAG_USER + 0x10001) #define MY_NumPoints (TTAG_USER + 0x10002) #define MY_Color (TTAG_USER + 0x10003) #define MY_Name (TTAG_USER + 0x10004)
A tag not containing TTAG_USER
is considered a control tag, which
determines how a single item is to be interpreted, or how an array
of tagitems should be traversed. The meanings of control tags are:
TTAG_DONE
End of the taglist; traversal stops at this item.
TTAG_IGNORE
tti_Value
of this item is to be ignored.TTAG_SKIP
The current item plus the number of items in
tti_Value
is to be ignored.TTAG_MORE
tti_Value
points to another taglist, at which traversal is to be continued. The control does not return to the current item.TTAG_GOSUB
tti_Value
points to another taglist, which is traversed recursively. After traversal, control returns to the current item.
Once a function is designed to accept a taglist argument, it becomes more flexible for future API changes. By assigning a default value to each tag argument, any number of new taglist arguments can be added to the function, without ever breaking existing code:
void API_func(TTAGITEM *tags) { TINT numv = (TINT) TGetTag(tags, MY_NumPoints, (TTAG) 3); TFLOAT *v = (TFLOAT *) TGetTag(tags, MY_Points, def_vertices); TSTRPTR n = (TSTRPTR) TGetTag(tags, MY_Name, "Def. Triangle"); TUINT rgb = (TUINT) TGetTag(tags, MY_Color, (TTAG) 0xff0000); /* ... more tags in the future ... */ }
- As the sizes of
TFLOAT
andTDOUBLE
types are not regulated in TEKlib, they should be transported as pointer references. Aside fromTTAG
type values and pointers, only integers (up to the size ofTUINTPTR
) should be placed into the fieldtti_Value
.
TEKlib lists are doubly-linked, with a stop node, which appears before the first and after the last node of a list.
The forward iterator for this topology looks like this:
struct TNode *next, *node = list->tlh_Head; for (; (next = node->tln_Succ); node = next) { /* * you can operate on 'node' here, remove it safely, * insert past it, as well as 'break' out from and * 'continue' the loop. */ }
TEKMain()
void TEKMain(struct TTask *task)
In a freestanding application, TEKlib resolves a platform-specific
entrypoint like main()
or intercepts the entrypoint provided by the
platform's binary loader, performs initializations with reasonable
defaults, and then enters TEKMain()
.
Resources such as argc
, argv
, return values and other properties
are made available to the framework in named atoms. See TEKCreate()
,
util:TGetArgC()
, util:TGetArgV()
, util:TSetRetVal()
for details.
If you need more control over the startup procedure then you can
write your own startup library using TEKCreate()
.
Unless you write a more convenient C++ startup library of your own, the TEKlib application entrypoint for a C++ application would look like this:
extern "C" void TEKMain(struct TTask *task) { /* ... */ }
teklib:TEKCreate()
, exec:TGetExecBase()
TEKCreate()
basetask = TEKCreate(tags) struct TTask* TTAGITEM*
This function creates an initial TEKlib context. All further
functionality is related to and derived from this handle.
If initialization fails, the return value is TNULL
. If successful,
the initial task handle refers to the process/thread context in which the
caller is running. The handle is being destroyed with a call to
teklib:TDestroy()
, which will clean up and free all resources.
This kind of startup allows for integratation of TEKlib into foreign environments, and you can use it for writing your own startup library.
basetask
- initial context handle.
tags
- Pointer to an array of tag items, orTNULL
.
TExecBase_ArgC, (TUINT)
- Submit amain()
entrypoint's number of arguments to the framework. If applicable,argc
,argv
will be made available in a named atomsys.argv
. See alsoutil:TGetArgC()
. Default: undefinedTExecBase_ArgV, (TSTRPTR)
- Submit amain()
entrypoint's array of arguments to the framework. If applicable,argc
,argv
will be made available in a named atomsys.argv
. See alsoutil:TGetArgV()
. Default: undefinedTExecBase_RetValP, (TINT *)
- Submit a pointer to a possible return value. The pointer will be made available in a named atomsys.returnvalue
. The variable being pointed to should be initialized with zero. See alsoutil:TSetRetVal()
for setting the return value in an application. Default: undefinedTExecBase_ModInit, (struct TInitModule *)
- Submit aTNULL
-terminated array of internal startup modules to your application. This allows you to link modules to applications statically. Internal modules will be looked up first, i.e. before any of the search strategies for modules from disk apply. Default:TNULL
TExecBase_ProgDir, (TSTRPTR)
- Override the path to TEKlib's logicalPROGDIR:
volume, which by default resembles to the directory in which the application resides. Default: the application directoryTExecBase_ModDir, (TSTRPTR)
- Some platforms support this tag argument for setting a global search path for modules, overriding the hardcoded internal default (e.g./opt/tek/mod
). Local modules (those inPROGDIR:mod
) are not affected, as those will always be probed first. Default: platform-specific.TExecBase_SysDir, (TSTRPTR)
- Some platforms support this tag argument for setting a global system directory, overriding the hardcoded internal default (e.g.C:\Programs\Common Shared Files\tek
), which also resembles to the logicalSYS:
volume in TEKlib's filesystem namespace. Default: platform-specific
- It is platform-specific whether you are allowed to create more than one instance of TEKlib per application. Most platforms currently supported do, but this would be something unadvisable to depend on.
- Applications running in the POSIX environment depend on the
argv
vector to determine their logical program directory. You are advised to pass the tagsTExecBase_ArgC
andTExecBase_ArgV
. If they are unavailable, useTExecBase_ProgDir
to supply this information.- Not all platforms support this kind of startup, since a fully-fledged TEKlib context cannot be described by the basetask handle alone. For example, if associating thread-specific data requires manipulation of the stack layout, then it is possible that the respective platform can only provide
TEKMain()
.
TAddHead()
TAddHead(list, node) struct TList* struct TNode *
Add a node at the head of a doubly linked list.
list
- Pointer to a list headernode
- Pointer to a node to be added
teklib:TAddTail()
, teklib:TInitList()
TAddTail()
TAddTail(list, node) struct TList* struct TNode *
Add a node at the tail of a doubly linked list.
list
- Pointer to a list headernode
- Pointer to a node to be added
teklib:TAddHead()
, teklib:TInitList()
TRemove()
TRemove(node) struct TNode*
Unlink a node from whatever list it is linked to.
node
- Pointer to a node to be removed
- Using this function with a node not being part of a list will be fatal.
teklib:TRemHead()
, teklib:TRemTail()
, teklib:TInitList()
TRemHead()
node = TRemHead(list) struct TNode* struct TList*
Unlink and return the first node from a doubly linked list.
node
- Pointer to the node being unlinked from the list, orTNULL
list
- Pointer to a list header
teklib:TRemTail()
, teklib:TRemove()
, teklib:TInitList()
TRemTail()
node = TRemTail(list) struct TNode* struct TList*
Unlink and return the last node from a doubly linked list.
node
- Pointer to the node being unlinked from the list, orTNULL
list
- Pointer to a list header
teklib:TRemHead()
, teklib:TRemove()
, teklib:TInitList()
TDestroy()
TDestroy(handle) struct THandle*
Destroy a generic handle by calling its destructor. If either
handle or handle->thn_DestroyFunc
is TNULL
, then nothing
will happen.
handle
- Pointer to a generic object handle
- No memory whatsoever will be freed by this function
teklib:TDestroyList()
, teklib:TFindHandle()
TInitList()
TInitList(list) struct TList*
Prepare a list header structure. After initialization the list will be empty and ready for use.
list
- Pointer to a list structure
TInsert()
TInsert(list, node, prednode) struct TList* struct TNode* struct TNode*
Insert a node into a list after prednode. If prednode
is TNULL
, then this function is equivalent to teklib:TAddTail()
.
list
- Pointer to a list to insert tonode
- Pointer to a node to insertprednode
- Pointer to a node in the list after which to insert
teklib:TRemove()
, teklib:TAddTail()
, teklib:TAddHead()
TNodeUp()
TNodeUp(node) struct TNode*
Move a node one position towards the head of the list it is linked to. In other words, if the node is not already at the head of the list, swap its position with its predecessor.
node
- Pointer to a node
- Using this function with a node not being part of a list will be fatal.
teklib:TRemove()
, teklib:TAddTail()
, teklib:TAddHead()
TGetTag()
value = TGetTag(taglist, tag, defvalue) TTAG TTAGITEM* TUINT TTAG
Parse a list of tag items and return the value associated with the first matching tag identifier. If the specified tag is not contained in the list, then the default value is returned.
taglists are arrays of tagitems. Each tagitem is composed from a key/value pair. Many TEKlib functions accept a taglist argument for making them more robust for future extensions.
The tag field can contain control tags and user tags. User tags must be combined with the TTAG_USER flag. Control tags are:
TTAG_DONE
This is the last entry of the array. traversal stops here.
TTAG_IGNORE
This item is being ignored.
TTAG_SKIP
Skip this item plus the number of items contained in value.
TTAG_MORE
Value is a pointer to another array oftagitems. Traversal is continued at the new array, and does not return.
TTAG_GOSUB
Value is a pointer to another array of tagitems. After return from the sub-array, traversal continues here.
value
- Value associated with the tag in the taglist, otherwise the default value
taglist
- Pointer to an array of tag itemstag
- Tag to be querieddefvalue
- Default value
- The
TTAG
type is capable of carrying pointers. This allows, in essence, to transport any kind of data in tag items, even on 64bit architectures. An unfortunate side-effect is that assigning a value totti_Value
may require a typecast toTTAG
for getting rid of complaints from the compiler.
TDestroyList()
TDestroyList(list) struct TList*
Unlinks all nodes from a list (in first-to-last order) and calls
teklib:TDestroy()
on each individual entry. Note that this function
expects all nodes (their heading structure) to be of the generic
handle datatype, otherwise the consequences would be nasty.
Nothing will happen if list is TNULL
or if the list is empty.
list
- list to clear
teklib:TDestroy()
, teklib:TFindHandle()
TNewInstance()
inst = TNewInstance(mod, possize, negsize) TAPTR TAPTR TUINT TUINT
This function creates a module instance copy. The module base can be duplicated alongside with a preceding function table.
possize
and {{negsize]] determine the size of the module base and the
size of a preceding function table, respectively. Usually these
arguments will be set to mod->tmd_PosSize
and mod->tmd_NegSize
,
which will create an exact copy a of the module. However, it is also
possible to extend the module base and function table.
A pointer to the duplicated module base is returned.
teklib:TNewInstance()
is typically used in a module's instance open
function.
inst
- A copy of the module base and function table, orTNULL
mod
- Pointer to module basepossize
- Positive size of the module, in bytesnegsize
- Negative size of the module, in bytes
The negative size is the size of the function table that normally precedes the module base.
teklib:TFreeInstance()
, teklib:TInitVectors()
TFreeInstance()
TFreeInstance(inst) struct TModule *
This function frees a module instance. It respects the size of the module base as well as its negative size, that is, the size of the function table preceding it.
This function is normally used in a module's instance close function.
inst
- Pointer to a module instance
teklib:TNewInstance()
, teklib:TInitVectors()
TInitVectors()
TInitVectors(mod, vectors, numv) TAPTR TAPTR* TUINT
This function takes a pointer to a table of function pointers and places them in front of a module base (in reverse order - a simple memory copy would be inappropriate here). This function is normally used in a module's init function.
mod
- Module base pointervectors
- Pointer to a table of function pointersnumv
- Number of entries
TFindHandle()
handle = TFindHandle(list, name) TAPTR TLIST* TSTRPTR
Find the first occurance of a named handle in a list. The name is expected in each node's handle->thn_Data field. Only lists containing only nodes with a conforming object handle may be searched with this function. Name comparison is case-sensitive.
handle
- Ptr to named handle, or TNULL if not found in the list
list
- Pointer to a list structurename
- Name of a handle to look up
teklib:TDestroy()
, teklib:TDestroyList()
TForEachTag()
(TODO)
complete = TForEachTag(taglist, function, userdata) TBOOL TTAGITEM* TTAGFOREACHFUNC TAPTR
This function traverses a list of tagitems, and for each item it calls a user-supplied function according of the following type:
TCALLBACK TBOOL function(TAPTR userdata, TTAGITEM *item)
The userdata
argument is passed to the callback function and
otherwise remains invisible to TForEachTag()
. The callback function
has to return TTRUE to continue traversal, or TFALSE to abort.
complete
- TTRUE if the list was traversed completely
When all items were traversed without interruption, then the
return value from TForEachTag()
will be TTRUE
. TFALSE
will be
returned otherwise.
taglist
- an array of tagitems to traversefunction
- callback function to call for each item traverseduserdata
- user data argument passed to the callback function
TInitHook()
TInitHook(hook, func, data) struct THook* THOOKFUNC TAPTR
Initialize a hook structure with a function and user data.
hook
- Hook structure to be initializedfunc
- C calling conventions function pointerdata
- User data to be associated with the hook
TEKlib hooks allow the transparent transition from e.g. register- to
stack-based calling conventions. hook->thk_Entry
is invoked by
teklib:TCallHookPkt()
and follows TEKlib's per-platform calling
conventions (as declared with THOOKENTRY
). It however may point
to a stub function calling the actual user function in
hook->thk_SubEntry
, which in turn may be entirely specific for
the used language or compiler.
TCallHookPkt()
result = TCallHookPkt(hook, object, message) TTAG struct THook* TAPTR TTAG
Invokes a hook function, passing it an object
and message
.
result
- specific to the invoked hook function
object
- An object to be processed by the hookmessage
- An action code
- TEKlib hooks are commonly used for destructors, hashing functions, module initialization, task creation, tag iterators etc. Therefore, TEKlib comes with a range of pre-defined hook message types, such as
TMSG_DESTROY
,TMSG_CALCHASH32
,TMSG_OPENMODULE
,TMSG_INITTASK
,TMSG_FOREACHTAG
, to name only examples. User-defined messages start atTMSG_USER
, but the user is free to bypass TEKlib's message codes altogether by seperating system hooks from his own.
SEE ALSO:
teklib:TInitHook()
TAddTime()
TAddTime(a, b) TTIME* TTIME*
Add time b
to time a
, leaving the result in time a
.
a
- Pointer to a time structure to add tob
- Pointer to a time structure to be added
TSubTime()
TSubTime(a, b) TTIME* TTIME*
Subtract time b
from time a
, leaving the result in time a
.
a
- Pointer to a time structure to subtract fromb
- Pointer to a time structure to be subtracted
teklib:TAddTime()
, teklib:TCmpTime()
, teklib:TSubDate()
TCmpTime()
res = TCmpTime(a, b) TINT TTIME* TTIME*
Compare time a
with time b
.
res
- result of comparison:
1
- if time a refers to a later point in time than time b-1
- if time a refers to a earlier point in time than time b0
- if time a is equal to time b.
a
- Pointer to a time structure, first operandb
- Pointer to a time structure, second operand
teklib:TAddTime()
, teklib:TSubTime()
, teklib:TDiffDate()
TAddDate()
TAddDate(date, ndays, time) TDATE* TINT TTIME*
Add a number of days and optionally a time to a date.
tdate
- Date structurendays
- Number of days to add. Can be 0.time
- Pointer to a TTIME structure. Can be TNULL.
- Do not add negative values in the time structure, use the function
teklib:TSubDate()
instead.
teklib:TSubDate()
, teklib:TDiffDate()
TSubDate()
TSubDate(date, ndays, time) TDATE* TINT TTIME*
Subtract a number of days and optionally a time from a date.
tdate
- Date structurendays
- Number of days to subtract. Can be 0.time
- Pointer to a TTIME structure. Can be TNULL.
- Do not subtract negative values in the time structure, use the function
TAddDate()
instead.
teklib:TAddDate()
, teklib:TDiffDate()
TDiffDate()
days = TDiffDate(date1, date2, timep) TINT TDATE* TDATE* TTIME*
This function returns the difference in number of days between date1 and date2. The difference in time will be inserted, optionally, into the time structure being pointed to by timep.
Note that if date1 is before date2, the resulting number of days will be negative, but the time difference (in seconds and microseconds) will always be inserted as positive numbers.
days
- Number of days difference
date1, date2
- Pointers to TDATE structurestimep
- Pointer to aTTIME
structure receiving a time difference, orTNULL
teklib:TAddDate()
, teklib:TSubDate()
TCreateTime()
success = TCreateTime(timep, d, s, us) TBOOL TTIME* TINT TINT TINT
This function composes a TEKlib time from days, seconds and microseconds.
success
- Boolean
timep
- Pointer to aTIME
structure receiving the resultd
- Number of dayss
- Number of secondsus
- Number of microseconds
teklib:ExtractTime()
, teklib:AddTime()
TExtractTime()
success = TExtractTime(timep, dp, sp, usp) TBOOL TTIME* TINT* TINT* TINT*
This function extracts from a TEKlib time the number of days, seconds and microseconds.
success
- Boolean
timep
- Pointer to aTIME
structuredp
- Pointer to a number of days, orTNULL
sp
- Pointer to a number of seconds, orTNULL
usp
- Pointer to a number of microseconds, orTNULL
TInitInterface()
TInitInterface(interface, module, name, version) struct TInterface* struct TModule* TSTRPTR TUINT16
This function initializes an interface structure.
interface
- Pointer to anTInterface
structuremodule
- Pointer to aTModule
structure to which the interface belongsname
- Name of the interfaceversion
- Version of the interface
TGetNextEntry()
entry = TGetNextEntry(handle) TAPTR struct THandle*
Get the next entry from a handle by dispatching TMSG_GETNEXTENTRY.
entry
- Next entry, orTNULL
if no next entry available
handle
- Pointer to a generic object handle
string:TStrCaseCmp()
- Compare strings, case-insensitive
string:TStrCat()
- Append string
string:TStrChr()
- Find character in a string
string:TStrCmp()
- Compare strings
string:TStrCpy()
- Copy string
string:TStrLen()
- Return length of a string
string:TStrNCaseCmp()
- Compare strings, case-insensitive, length-limited
string:TStrNCat()
- Append string, length-limited
string:TStrNCmp()
- Compare strings, length-limited
string:TStrNCpy()
- Copy string, length-limited
string:TStrRChr()
- Find character in a string from the end
string:TStrStr()
- Find substring in a string
string:TStrToI()
- Convert string to integer
TStrNCpy()
dest = TStrNCpy(dest, source, maxlen) TSTRPTR TSTRPTR TSTRPTR TSIZE
- If the length of
source
is less thanmaxlen
, this function does not pad the remainder of dest with null bytes. This is in contrast to thestrncpy()
standard library function.
TStrCmp()
res = TStrCmp(first, second) TINT TSTRPTR TSTRPTR
- Either or both strings may be
TNULL
. ATNULL
string is 'less than' a non-TNULL
string.
TStrNCmp()
res = TStrNCmp(first, second, maxlen) TINT TSTRPTR TSTRPTR TSIZE
See annotations for
string:TStrCmp()
TStrCaseCmp()
res = TStrCaseCmp(first, second) TINT TSTRPTR TSTRPTR
See annotations for
string:TStrCmp()
TStrNCaseCmp()
res = TStrNCaseCmp(first, second, maxlen) TINT TSTRPTR TSTRPTR TSIZE
See annotations for
string:TStrCmp()
TStrToI()
numchars = TStrToI(string, valp) TINT TSTRPTR TINT*
This function converts a string to a 32bit signed integer.
numchars
- Number of characters converted, or:
-1
- Conversion error, invalid characters-2
- Overflow or underflow occured
string
- Pointer to a string to be convertedvalp
- Pointer to a value to be filled in by this function
exec:TAbortIO()
- Ask for abortion of an I/O packet
exec:TAckMsg()
- Acknowledge a message to its sender
exec:TAlloc()
- Allocate memory
exec:TAlloc0()
- Allocate memory, blank
exec:TAllocMsg()
- Allocate memory for a message
exec:TAllocMsg0()
- Allocate memory for a message, blank
exec:TAllocPool()
- Allocate memory from a pooled allocator
exec:TAllocSignal()
- Allocate a signal bit from a task
exec:TAllocTimeRequest()
- Allocate a timer device request
exec:TCheckIO()
- Check for completion of an I/O packet
exec:TCloseModule()
- Close a module or module instance
exec:TCopyMem()
- Copy memory
exec:TCreateLock()
- Create locking object for sharing a resource
exec:TCreateMemManager()
- Create a memory manager
exec:TCreatePool()
- Create pooled memory allocator
exec:TCreatePort()
- Create a message port for communication
exec:TCreateSysTask()
- Create Exec system task
exec:TCreateTask()
- Create a new thread of execution
exec:TDoExec()
- Perform initializations and service Exec system tasks
exec:TDoIO()
- Send (and wait for) an I/O packet synchronously
exec:TDropMsg()
- Make a message fail at its sender
exec:TFillMem()
- Fill memory
exec:TFindTask()
- Find own or a named task
exec:TFree()
- Free memory
exec:TFreePool()
- Return memory to a pool
exec:TFreeSignal()
- Return an allocated signal bit to a task
exec:TFreeTimeRequest()
- Free a timer device request
exec:TGetAtomData()
- Get data associated with an atom
exec:TGetExecBase()
- Get Exec module base pointer
exec:TGetHALBase()
- Get HAL module base pointer
exec:TGetLocalDate()
- Get system's local date and time
exec:TGetMemManager()
- Get an allocation's memory manager
exec:TGetMsg()
- Get a message from a message port
exec:TGetPortSignal()
- Get a message port's underlying signal bit
exec:TGetSize()
- Get size of an allocation
exec:TGetSyncPort()
- Get a task's port for synchronized messages
exec:TGetSystemTime()
- Get a (relative) system time
exec:TGetTaskData()
- Get a task's user data pointer
exec:TGetTaskMemManager()
- Get a task's memory manager
exec:TGetUniversalDate()
- Get universal date and time (UTC)
exec:TGetUserPort()
- Get a task's inbuilt user message port
exec:TLock()
- Gain access to a shared resource
exec:TLockAtom()
- Gain access to a named atom
exec:TOpenModule()
- Open a module or module instance
exec:TPutIO()
- Put an I/O packet to a device or handler, asynchronously
exec:TPutMsg()
- Send a message to a task, asynchronously
exec:TQueryInterface()
- Obtain an interface from an open module
exec:TRealloc()
- Resize an allocated block of memory
exec:TReallocPool()
- Resize an allocation made from a pool
exec:TReplyMsg()
- Return a modified message to its sender
exec:TScanModules()
- Scan available TEKlib modules
exec:TSendMsg()
- Send a message synchronously
exec:TSetAtomData()
- Set data associated with an atom
exec:TSetSignal()
- Set and get a task's signal state
exec:TSetTaskData()
- Set a task's user data pointer
exec:TSignal()
- Submit signals to a task
exec:TUnlock()
- Release access to a shared resource
exec:TUnlockAtom()
- Release access to a named atom
exec:TWait()
- Wait for signals
exec:TWaitDate()
- Wait for an absolute date or a set of signals
exec:TWaitIO()
- Wait for completion of an I/O packet
exec:TWaitPort()
- Wait for a single message port
exec:TWaitTime()
- Wait for a timeout or a set of signals
TGetExecBase()
TExecBase = TGetExecBase(object) struct TExecBase* TAPTR
This macro retrieves a pointer to the Exec module base from an Exec object. Objects provided by the Exec module are tasks, ports, memory managers, atoms, locks, and modules themselves.
TExecBase
- Pointer to the Exec module base
object
- Pointer to an Exec object
The TEKlib framework is free of global data and carefully designed to be fully reentrant. It is the programmer's choice to put module base pointers into global variables.
Initially, an application is entered with a task handle only. It is usually required to query the Exec module base pointer from that handle before anything useful can be done. The module base pointer can then be stored in a global variable, if desired. A typical application startup may look like this:
struct TExecBase *TExecBase; struct TUtilBase *TUtilBase; void TEKMain(struct TTask *task) { TExecBase = TGetExecBase(task); TUtilBase = TOpenModule("util", ... ... }
TDoExec()
success = TDoExec(cmd, tags) TBOOL TUINT TTAGITEM*
Runs or initializes an Exec context. Depending on the cmd
argument, TDoExec()
performs missing initializations in the current task
or services module opens, task creation and atom lookups.
It is expected that the thread context in which this function is called
was previously created using exec:TCreateSysTask()
.
success
- Boolean
cmd
- Type of service to provide:
TEXEC_CMD_INIT
- Performs initializations that qualify the current context as TEKlib's main application task. After returning, the user function can be called in a fully-fledged Exec context.TEXEC_CMD_EXIT
- Performs the required steps to shut down and free all resources in the application taskTEXEC_CMD_RUN
- If the caller's task name isTTASKNAME_EXEC
("exec"
) then this function will serve module opens, task creation and atom lookups, requested through the message portexecbase->texb_ExecPort
. If the name isTTASKNAME_RAMLIB
("ramlib"
), this function will serve requests for loading modules, submitted to the task's userport. Either way, it returns to the caller when it receives the signalTTASK_SIG_ABORT
.
tags
- Pointer to an array of tag items (none currently defined)
This function is of any use only for implementors of startup libraries.
exec:TCreateSysTask()
, exec:TCreateTask()
TCreateSysTask()
task = TCreateSysTask(func, tags) struct TTask* TTASKFUNC TTAGITEM*
This function creates an Exec-internal task. If func
is TNULL
,
a TEKlib task is placed in the caller's thread context, otherwise a new
thread of execution is started at the given function.
This function is used to setup an initial TEKlib context (or an Exec task) before TEKlib is fully initialized. This function is not entirely safe in regular applications and the only sanctioned use is in startup libraries.
task
- Task handle, or TNULL
if initialization failed
func
- Pointer to a thread entry function, or TNULL
for the
current context
tags
- Pointer to an array of tag items:
TTask_Name (TSTRPTR)
- Pointer to a string for the task name. Default:TNULL
TTask_UserData (TAPTR)
- Pointer to an initial user data packet. Default:TNULL
exec:TCreateTask()
.
exec:TCreateTask()
, exec:TDoExec()
, exec:TGetTaskData()
TGetHALBase()
THALBase = TGetHALBase() struct THALBase *
Returns a pointer to the HAL module base. Access to the HAL layer is often required in device driver implementations.
THALBase
- HAL module base pointer
TOpenModule()
modbase = TOpenModule(name, version, tags) struct TModule* TSTRPTR TUINT16 TTAGITEM*
Opens a module or a module instance. When the module's version is greater or equal the requested version and when the module can be loaded and initialized successfully, a pointer to the module base will be returned to the caller.
modbase
- Module base or TNULL
. TNULL
is returned if
the module could not be found, when it failed to initialize or when
the version requirement could not be satisfied.
name
- Name of the module
version
- Minimal module version for the open to succeed
tags
- Pointer to an array of tag items. Tags passed to
this function are passed to the module open function and can be
intercepted there. There are currently no tags defined for
exec:TOpenModule()
itself.
TCloseModule()
, or TEKlib will panic at exit.
exec:TCloseModule()
, exec:TGetExecBase()
TCloseModule()
TCloseModule(modbase) struct TModule *
Closes a module or a module instance. When applied to the last reference or instance open then the module will be deinitalized, unloaded and freed.
module
- Module or module instance. It is safe to pass TNULL
.
TCopyMem()
TCopyMem(source, dest, numbytes) TAPTR TAPTR TSIZE
Copy the given number of bytes from a source to a destination address in memory.
source
- Source address
dest
- Destination address
numbytes
- Number of bytes to copy
- Do not rely on overlapping copies to work with this function.
TFillMem()
TFillMem(start, numbytes, fillval) TAPTR TSIZE TUINT8
Fill a range of memory with a 8bit value.
start
- Start address in memory
numbytes
- Number of bytes to fill
fillval
- 8bit value
TCreateMemManager()
memmanager = TCreateMemManager(resource, type, tags) struct TMemManager* TAPTR TUINT TTAGITEM*
Create a memory manager. A memory manager can be passed to exec:TAlloc()
for allocating memory with special functionality attached to it, such as
automatic cleanup, tighter packing, thread-safety, etc. Memory managers
can be stacked on top of each other.
A memory manager is freed with a call to teklib:TDestroy()
.
TNULL
is always a valid memory manager. A TNULL
memory manager
will cause exec:TAlloc()
to use the system's general purpose allocator.
Only a TNULL
memory manager is intrinsically safe to use in a
multitasking environment; other allocators must implement cross-task
protection explicitely. See the TMMT_TaskSafe
flag for details.
memmanager
- Memory manager, or TNULL
if initialization failed.
resource
- Memory resource object, parent memory manager or TNULL
type
- Type of memory manager to be created:
TMMT_MemManager
- Setup a memory manager on top of another, implementing no additional functionality.resource
must beTNULL
or point to another memory manager.TMMT_TaskSafe
- Setup a memory manager implementing thread-safety. Multiple tasks are allowed to operate on the resulting memory manager at the same time.TMMT_Tracking
- Setup a tracking memory manager. The resulting memory manager will return all pending allocations to its parent when it is being destroyed, at the cost of extra performance and resource usage. This type can be combined withTMMT_TaskSafe
.TMMT_Static
- The resulting memory manager will manage a static block of memory. When the block is exhausted or fragmented, further allocations will fail, as no attempts are made to get more storage from the outside.resource
must be a pointer to a block of memory orTNULL
. The tagTMem_StaticSize
must be specified in the taglist as well (see below). This type can be combined withTMMT_TaskSafe
.TMMT_Pooled
- The resulting memory manager will group small allocations into larger ones. All pending allocations will be freed when the memory manager is being destroyed.resource
must be a pointer to a pool created withexec:TCreatePool()
orTNULL
. In the latter case, a pooled allocator will be created and maintained internally with the resulting memory manager, and any pool-specific tags passed to this function will be used accordingly. Seeexec:TCreatePool()
for details. This type can be combined withTMMT_TaskSafe
.TMMT_Void
- The resulting memory manager will be incapable of allocating memory. Attempts to do so will always returnTNULL
. This type can be useful for debugging purposes.
tags
- Pointer to an array of tag items:
TMem_StaticSize, (TSIZE)
- This argument is mandatory whentype
isTMMT_Static
. The value specifies the size of the block of memory to be managed.resource
must be a pointer to a block of memory of this size, orTNULL
. In the latter case, a block of this size will be allocated and maintained internally, and freed when the resulting memory manager is getting destroyed. Default:0
TMem_LowFrag, (TBOOL)
- This tag is considered whentype
isTMMT_Static
. It will cause the resulting memory manager to use an allocation strategy that helps reducing the internal fragmentation, at the cost of performance. This is also known as the 'best match' strategy. The default is the 'first match' strategy. Default:TFALSE
TAlloc()
mem = TAlloc(memmanager, size) TAPTR struct TMemManager* TSIZE
This function allocates a block of memory from a memory manager.
A pointer to the allocated block of memory is returned, or TNULL
if the request cannot be satisfied. A TNULL
memory manager is valid
and directs requests to the system's general purpose allocator.
mem
- Pointer to a block of memory, or TNULL
if out of memory
memmanager
- Pointer to a memory manager, or TNULL
size
- Size of the allocation [bytes]
exec:TAlloc0()
to get a blank allocation.
exec:TAllocMsg()
for details.
TAlloc0()
mem = TAlloc0(memmanager, size) TAPTR struct TMemManager* TSIZE
Allocate a blank block of memory from a memory manager. This
function is equivalent to TAlloc()
except for that the returned
memory is guaranteed to be filled with all bytes set to zero.
mem
- Pointer to a block of memory, or TNULL
if memory resource
exhausted
memmanager
- Pointer to a memory manager or TNULL
size
- Size of the allocation [bytes]
TQueryInterface()
interface = TQueryInterface(module, name, version, tags) struct TInterface* struct TModule* TSTRPTR TUINT16 TTAGITEM*
This function queries a module for an interface of the given name and
version. Returns TNULL
if no interface could be found or created.
The resulting interface structure must be freed with a matching
call to teklib:TDestroy()
prior to closing the module from which it was
obtained.
interface
- Pointer to an interface structure
module
- Module to obtain the interface fromname
- Name of the interfaceversion
- Minimum version of the interfacetags
- Additional tags, passed to the module dispatch hook in an object of the typestruct TInterfaceQuery
via the fieldobject->tifq_Tags
.
SEE ALSO:
exec:TOpenModule()
, teklib:TDestroy()
TFree()
TFree(mem) TAPTR
Return a block of memory to the memory manager it was allocated from.
mem
- Block of memory to be freed. It is safe to pass TNULL
.
exec:TAlloc()
or exec:TAllocMsg()
. It cannot be used
for memory that was obtained from a pool or via the standard
libraries.
TRealloc()
newmem = TRealloc(oldmem, newsize) TAPTR TAPTR TSIZE
Resize a block of memory that was allocated from a memory
manager. If newsize
is 0
, the block of memory will be freed
and the result will be TNULL
.
This function departs from the usual realloc semantics in that it cannot
be used to allocate a fresh block of memory. If a TNULL
pointer is
passed as the oldmem
argument, this function returns TNULL
.
If a reallocation fails and the return value is TNULL
, the old
block of memory still belongs to the user.
newmem
- Pointer to memory reallocated to newsize, or TNULL
oldmem
- Pointer to memory allocated
newsize
- New size for the allocation or 0
exec:TAlloc()
. It cannot be used for memory that
was obtained from pools or via the standard libraries.
TGetMemManager()
memmanager = TGetMemManager(mem) struct TMemManager* TAPTR
Returns a pointer to the memory manager an allocation was made from.
memmanager
- Pointer to a memory manager
mem
- Pointer to a block of memory
TNULL
is a valid memory manager, referring to
the system's general-purpose allocator.
exec:TGetSize()
, exec:TAlloc()
, exec:TCreateMemManager()
TGetSize()
size = TGetSize(mem) TSIZE TAPTR
This function gets the size of a block of memory (in bytes) that was allocated from a memory manager.
size
- size of the allocation [bytes]
mem
- Pointer to a block of memory
exec:TGetMemManager()
, exec:TAlloc()
TCreateLock()
lock = TCreateLock(tags) struct TLock* TTAGITEM*
Create a locking object. A lock is a mechanism to protect resources from simultaneous accesses from multiple tasks. Only one accessor can hold the same lock at a given time.
A lock is destroyed with a call to teklib:TDestroy()
.
lock
- Lock created, or TNULL
if creation failed
tags
- Pointer to an array of tag items (none defined yet)
exec:TLock()
per calling task must be paired with
exactly one matching call to exec:TUnlock()
.
exec:TLock()
, exec:TUnlock()
, teklib:TDestroy()
TLock()
TLock(lock) struct TLock*
Gain exclusive access to a lock. If another task is currenty holding the lock, the caller will block until the lock is free. If no other task holds the lock, then this function returns immediately with exclusive access.
This function is recursive (or 'nesting'), i.e. it may be called subsequently when the lock is already held by the current owner. In that case an internal counter is increased and this function returns immediately with a lock on the shared resource.
Each call per task must be paired with exactly one matching call
to exec:TUnlock()
, which will decrease the nesting counter. When
the counter reaches zero, the control is handed over to the next
waiter or, if there are no waiters, the lock is being released.
lock
- Pointer to a lock created with exec:TCreateLock()
exec:TUnlock()
, exec:TCreateLock()
TUnlock()
TUnlock(lock) struct TLock*
Release access to a lock which was previously obtained with
a call to exec:TLock()
. The next task currently suspended waiting
for the lock will gain exclusive access to the resource and
resume.
lock
- Pointer to a locking object in locked state
exec:TLock()
, exec:TCreateLock()
TAllocSignal()
signals = TAllocSignal(prefsignals) TUINT TUINT
Allocate a signal (or a set of preferred signals) from the
current task. If prefsignals is 0
then this function will try to
reserve any single free signal. Otherwise, this function tries to
reserve the exact set specified.
signals
- Signals allocated. 0
if out of signals, or if any
of the signal bits in prefsignals
is already in use.
prefsignals
- Preferred set of signals or 0
for any free signal
exec:TFreeSignal()
.
TFreeSignal()
TFreeSignal(signals) TUINT
Free a single or a set of signals and return them to a task's signal pool.
signals
- Signal mask to be freed. It is safe to pass 0
.
exec:TAllocSignal()
, exec:TWait()
TSignal()
TSignal(task, signals) struct TTask* TUINT
Submit signals to a task. The signal(s) will show up in the signalled task. When the task was suspended waiting for any of the specified signals, it will resume its operation.
task
- Task to be signalled
signals
- A set of signals to be submitted
exec:TSetSignal()
, exec:TWait()
, exec:TAllocSignal()
TSetSignal()
oldsignals = TSetSignal(newsignals, sigmask) TUINT TUINT TUINT
Set the current task's signal state to the signal bits in
newsignals
, masked through the bits in the sigmask
argument,
and return the old state of the tasks's signals to the caller.
newsignals
- New set of signals
sigmask
- Signal bits to be affected
/* get the current state of all signals, but do not modify them */ signals = TSetSignal(0, 0); /* clear the TTASK_SIG_ABORT signal */ TSetSignal(0, TTASK_SIG_ABORT);
exec:TSignal()
, exec:TWait()
, exec:TAllocSignal()
TWait()
signals = TWait(sigmask) TUINT TUINT
Suspend the current task to wait for one or more of the signals specified
in sigmask
to arrive. Those bits will be cleared from the task's
signal state and returned to the caller when the function returns. If
sigmask
is 0
, this function will immediately return 0
.
signals
- Signals that caused returning
sigmask
- Set of signals to wait for
TCreatePort()
port = TCreatePort(tags) struct TMsgPort* TTAGITEM*
Create a message port owned by the current task.
A message port is an access point for messages between tasks. It
can be synchronized on using exec:TWaitPort()
. Use exec:TGetPortSignal()
to retrieve a port's underlying signal. Using this signal, one or more
message ports can be synchronized on using exec:TWait()
.
A message port is destroyed with a call to teklib:TDestroy()
.
port
- Message port created, or TNULL
if failed
tags
- Pointer to an array of tag items (none defined yet)
exec:TGetUserPort()
. Use exec:TCreatePort()
to create
more ports if necessary.
TPutMsg()
TPutMsg(msgport, replyport, msg) struct TMsgPort* struct TMsgPort* TAPTR
Put a message to a message port. If a replyport
is specified, the
message will be sent two-way, and there will be a reply expected at
this port. If replyport
is TNULL, the message will be sent
one-way and does not return to the sender.
msgport
- Addressed message port
replyport
- Message port for the reply or TNULL
msg
- Message to be sent
TGetMsg()
msg = TGetMsg(msgport) TAPTR struct TMsgPort*
Unlink the next pending message from a port's message queue and
return it to the caller. This function does not block; if the
message queue is empty, this function returns immediately with TNULL
.
msg
- Next pending message or TNULL
if the queue was empty
msgport
- Message port to get next message from
TAckMsg()
TAckMsg(msg) TAPTR
Acknowledge a two-way message to its sender, i.e. return it to the replyport that was specified by the sender when the message was sent.
It is safe to apply this function to one-way messages as well; if the message was sent without the expectation of a reply or acknowledgement, it will silently be freed by returning the memory to its memory manager.
When a message is returned with this function, the sender must not
rely on modifications made inside the message body. If a changed
message is to be returned, then exec:TReplyMsg()
should be used instead.
msg
- Message to be acknowledged or to be freed, transparently
exec:TAckMsg()
and exec:TReplyMsg()
is
meaningless in local address space, but it may become useful in the
future.
TReplyMsg()
TReplyMsg(msg) TAPTR
Reply a two-way message to its sender, i.e. return it to the replyport that was specified by the sender when the message was sent.
It is safe to apply this function to one-way messages as well; if the message was sent without the expectation of a reply or acknowledgement, it will silently be freed by returning the memory to its memory manager.
Use this function for transferring a modified message body back to
its sender. If the message was not modified and it is only required
to inform the sender that it has been processed, then exec:TAckMsg()
should be used instead.
msg
- Message to be replied (or to be freed, transparently)
exec:TAckMsg()
and exec:TReplyMsg()
is
meaningless in local address space, but it may become useful in the
future.
exec:TAckMsg()
, exec:TDropMsg()
, exec:TPutMsg()
, exec:TAllocMsg()
TDropMsg()
TDropMsg(msg) TAPTR
Abandon a two-way message, i.e. return it to its replyport with the
internal message status set to TMSG_STATUS_FAILED
. This function is
not guaranteed to return any modifications made inside the message
body, it will only indicate failure.
It is safe to apply this function to one-way messages as well; if the message was sent without the expectation of a reply or acknowledgement, it will silently be freed by returning the memory to its memory manager.
In local address space this function is particularly useful for
indicating failure to the caller of exec:TSendMsg()
.
msg
- Message to be abandoned (or to be freed, transparently)
TSendMsg()
status = TSendMsg(port, msg) TUINT struct TMsgPort* TAPTR
This function sends a message two-way, synchronized, waiting for a reply or an acknowledgement before it returns to the caller.
The return value will be set to TMSG_STATUS_FAILED
if the
message has been dropped, or, depending on the return method,
TMSG_STATUS_REPLIED
or TMSG_STATUS_ACKD
if it returned
successfully.
status
- delivery status of the message:
TMSG_STATUS_FAILED
if the message was droppedTMSG_STATUS_REPLIED
if repliedTMSG_STATUS_ACKD
if acknowledged
port
- Message port to send message to
msg
- Message to be sent
TWaitPort()
msg = TWaitPort(port) TAPTR struct TMsgPort*
Suspend the current task to wait for a message to arrive at the
given message port. When a message is already present then this
function returns immediately. A pointer to the next pending
message is returned to the caller, but it is not removed from
the queue. Use TGetMsg()
to unlink the next message from a port.
msg
- Next pending message in the queue
port
- Message port
exec:TGetPortSignal()
to combine the signals from multiple
message ports and synchronize on them using exec:TWait()
.
TGetPortSignal()
signal = TGetPortSignal(port) TUINT struct TMsgPort*
This function retrieves a message port's underlying signal.
The typical use of that signal is to use exec:TWait()
to combine
waiting for messages from multiple ports.
signal
- The signal that shows up in the port's task
port
- Message port to get signal from
exec:TCreatePort()
, exec:TWait()
, exec:TWaitPort()
TGetUserPort()
userport = TGetUserPort(task) struct TMsgPort* struct TTask*
Get a pointer to a task's primary, asynchronous message port,
which is reserved for the user. If the task argument is TNULL
,
the caller's own task will be queried.
Each task is supplied with an user port upon creation. More
message ports can be created using exec:TCreatePort()
during a
task's lifetime.
userport
- Pointer to task's userport
task
- Task handle, or TNULL
TTASK_SIG_USER
.
TGetSyncPort()
syncport = TGetSyncPort(task) struct TMsgPort* struct TTask*
Get a pointer to a task's inbuilt syncport. If task is TNULL
,
the caller's own task will be addressed.
The syncport is reserved for synchronized message replies. It can be employed by the user if its usage remains strictly limited to that purpose.
For instance, it is not allowed to send messages using exec:TPutMsg()
expecting a reply at a syncport. This would break Exec functions
that might use the syncport (or the syncport's signal) internally.
For asynchronous message communication use the task's user port,
or create a new port using exec:TCreatePort()
.
syncport
- Pointer to task's syncport
task
- Task handle, or TNULL
TCreateTask()
task = TCreateTask(hook, taglist) struct TTask* struct THook* TTAGITEM*
Creates a task, launches a new thread of execution and invokes the
supplied hook with the message TMSG_INITTASK
in the newly
created context. A return value of TFALSE
from the hook function
causes this function to abandon task creation and to return TNULL
.
If the return value is TTRUE
, TCreateTask()
returns the
newly created task handle to the caller, and invokes the hook again,
this time with the message TMSG_RUNTASK
.
The task handle is destroyed with a call to teklib:TDestroy()
.
This will synchronize on the task's completion and free its
resources. TEKlib tasks must always leave gently through their
function exit, and all task must be synchronized on properly,
or the TEKlib framework panics at exit.
task
- Task handle, or TNULL
if the task could not be
established
hook
- Task initialization hook. Note: TCreateTask()
will
operate on an internal copy of this structure, to allow the caller
to place it on the stack and to throw it away after task creation.
taglist
- Pointer to an array of tag items:
TTask_UserData, TAPTR
- Pointer to a initial user data pointer that will be attached to the newly created task. It can be queried from the task handle usingexec:TGetTaskData()
. Default:TNULL
TTask_Name, TSTRPTR
- Pointer to the task's name. If a name is supplied, the task can be found usingexec:TFindTask()
. Default:TNULL
TTask_CurrentDir, TAPTR
- With this argument, a directory lock can be specified that will be duplicated and used as the new task's current directory. By default, tasks inherit their current directory from their parent. Default: The caller's current directoryTTask_InputFH, (TAPTR)
TTask_OutputFH, (TAPTR)
TTask_ErrorFH, (TAPTR)
- These tags allow the caller to pass file handles to the newly created task for standard input, ouput and error, respectively. By default, the I/O handles for newly created tasks are unset and opened on demand, that is, by the io module in attempts to open the files "stdio:in", "stdio:out" or "stdio:err", respectively.
TFindTask()
task = TFindTask(name) struct TTask* TSTRPTR
Find a named task in the system. If name is TNULL
then this function
will return a pointer to the caller's own task.
task
- Pointer to a task handle or TNULL
if not found
name
- Name of a task or TNULL
for finding the caller's own task
TGetTaskData()
userdata = TGetTaskData(task) TAPTR struct TTask*
Get a pointer to a task's user data. A user data pointer can be
supplied upon task creation using the TTask_UserData
tag, and be set
or overwritten using exec:TSetTaskData()
during a task's lifetime.
userdata
- Pointer to a task's user data
task
- Task handle or TNULL
to query the caller's own task
exec:TSetTaskData()
, exec:TCreateTask()
TSetTaskData()
olddata = TSetTaskData(task, userdata) TAPTR TAPTR TAPTR
Set a task's user data pointer and return the previous user data pointer to the caller.
A user data pointer can be supplied upon task creation using the
TTask_UserData
tag and queried with exec:TGetTaskData()
during
a task's lifetime.
olddata
- Pointer to task's previous user data
task
- Task handle or TNULL
to address the caller's own task
userdata
- New data to associate with the task
exec:TGetTaskData()
, exec:TCreateTask()
TGetTaskMemManager()
memmanager = TGetTaskMemManager(task) struct TMemManager* struct TTask*
Get a pointer to a task's inbuilt memory manager. Allocations made from this memory manager are automatically freed when the task exits.
memmanager
- Task's memory manager
task
- Task handle, or TNULL
to query the caller's own task
exec:TAlloc()
, exec:TCreateMemManager()
TAllocMsg()
msg = TAllocMsg(size) TAPTR TSIZE
Allocate memory for a message. Message allocations behave largely
like regular allocations, but they originate from their own clsss of
memory manager. Use exec:TFree()
to return a message to its memory
manager. exec:TGetSize()
and exec:TGetMemManager()
are valid also.
msg
- Pointer to message memory, or TNULL
if failed
size
- Size of the requested block of memory [bytes]
TNULL
.
exec:TAllocMsg0()
to get a
blank message.
TAllocMsg0()
msg = TAllocMsg0(size) TAPTR TSIZE
Allocate memory for a message, blank. This function is equivalent
to exec:TAllocMsg()
, except for that the message returned is
guaranteed to be filled with all bytes set to zero.
mem
- Pointer to message memory, or TNULL
if failed
size
- Size of the requested block of memory [bytes]
TLockAtom()
atom = TLockAtom(data, mode) struct TAtom* TATPR TUINT
Depending on the mode argument, this function creates, obtains or destroys a named atom. Atoms are an extension to locks, allowing multiple accessors to create, locate and access resources by name. Also, atoms allow shared locking and locking attempts.
Atoms are recursive. This means the same task holding a lock on an atom is allowed to claim it subsequently, and this function returns with a nesting lock immediately. All locks per task must be paired with exactly one matching unlock operation.
Once locked by the caller, a data field can be associcated with an
atom using exec:TSetAtomData()
and retrieved with exec:TGetAtomData()
.
atom
- Pointer to an atom in locked state, or TNULL
if failed
data
- Pointer to an existing atom or to a name
mode
- Access modes and flags:
By special convention,
TATOMF_NAME
- This flag indicates that the data argument is expected to be a pointer to a name. Otherwise it's expected to be a pointer to an existing atom.TATOMF_KEEP
- If data is a pointer to a name and if no atom of that name existed,TNULL
is returned. Otherwise this function returns with a lock on the atom. Atom is returned.TATOMF_CREATE
- If combined withTATOMF_NAME
and if an atom of that name did not exist, it is created and returned in locked state. ReturnsTNULL
if out of resources.TATOMF_DESTROY
- If the atom exists then it is locked and destroyed. If the atom does not exist or if the mode is combined withTATOMF_TRY
and the atom is in use elsewhere,TNULL
is returned. Otherwise a non-TNULL
value is returned.TATOMF_TRY
- If the atom is currently locked exclusively, returns immediately withTNULL
. If the atom is currently locked shared, then attempts to lock it exclusively return immediately withTNULL
. Also returnsTNULL
if combined withTATOMF_CREATE
andTATOMF_NAME
and when an atom of that name already exists.TATOMF_SHARED
- Lock in shared mode. Multiple tasks claiming a shared atom at the same time can succeed. If an atom is currently held exclusively then all shared lockers will block until the exclusive lock is released. If an atom is locked in shared mode, attempts to lock it exclusively will block until the atom is free.
TATOMF_CREATE|TATOMF_SHARED
returns with
a shared lock only if an atom of that name already existed. If
an atom of that name did not exist, it is created and returned
in exclusively locked state; this allows to safely associate an
initial data packet to an atom that is used in shared mode later.
TATOMF_CREATE
without TATOMF_NAME
will currently return TNULL
.
The combination of TATOMF_CREATE
and TATOMF_DESTROY
is undefined.
TUnlockAtom()
TUnlockAtom(atom, mode) struct TAtom* TUINT
Release access to an atom that has been locked with exec:TLockAtom()
.
atom
- Atom in locked state
mode
- Unlocking modes:
TATOMF_KEEP
- Release onlyTATOMF_DESTROY
- Release and destroy the atom
TGetAtomData()
data = TGetAtomData(atom) TTAG struct TAtom*
Query an atom's user data tag. The atom should be in locked state and currently being owned by the caller.
data
- Atom's user data
atom
- Atom, as returned by exec:TLockAtom()
exec:TSetAtomData()
, exec:TLockAtom()
TSetAtomData()
olddata = TSetAtomData(atom, data) TTAG struct TAtom* TTAG
Associate a user data tag with an atom. The atom should be in exclusively locked state and currently being owned by the caller.
olddata
- Previous data tag
atom
- Atom, as returned by TLockAtom()
data
- User data tag to be associated
exec:TGetAtomData()
, exec:TLockAtom()
TCreatePool()
pool = TCreatePool(tags) struct TMemPool* TTAGITEM*
Create a memory pool. A pool is an allocator that groups small
allocations into larger ones. All pending allocations made from
a pool will be returned to the pool's underlying memory manager
once the pool is being destroyed with a call to teklib:TDestroy()
.
Pools grow and shrink on demand. Two parameters constitute
their behavior:
- Pudsize is the size of a 'puddle', i.e. a regular chunk of memory that will be allocated from an underlying memory manager when a request cannot be satisfied from the current set of puddles. Many small allocations can fit into a puddle.
- Thressize is the maximum size of allocations that go into regular puddles. Allocations larger than that will go into puddles of their own. Thressize must be less or equal pudsize.
Both pudsize and thressize can be supplied in taglist arguments and remain constant during a pool's lifetime. By default, though, TEKlib pools try to determine appropriate settings for pudsize and thressize during a pool's lifetime and adapt these parameters dynamically.
Pools can be useful for sections of code that mainly deal with many objects of relatively constant sizes. Allocations in a pool are more tightly packed and on smaller boundaries than general-purpose allocations.
pool
- Pointer to a pooled allocator or TNULL
if failed
tags
- Pointer to an array of tag items:
TPool_MemManager, (TAPTR)
- Pool's underlying memory manager - this is where puddles will be allocated from.TPool_PudSize, (TUINT)
- Initial size of puddles [bytes]. WhenTPool_AutoAdapt
is enabled, this value can change during a pool's lifetime. Default:1024
TPool_ThresSize, (TUINT)
- Initial threshold size for allocations that go into regular puddles [bytes]. This value must be less than or equal pudsize. WhenTPool_AutoAdapt
is enabled, this value can change during a pool's lifetime. Default:256
TPool_AutoAdapt, (TBOOL)
- Use a simple runtime analysis to adapt a pool's pudsize and thressize to the requirements during its lifetime. Currently thressize tends to 4 times the average size of allocations and pudsize tends to 8 times of thressize. Default:TTRUE
TMem_LowFrag, (TBOOL)
- Use an allocation strategy that may help to reduce a pool's internal fragmentation, at the cost of some extra performance. This is also known as the 'best match' strategy. The default is the 'first match' strategy. default:TFALSE
exec:TCreateMemManager()
for details.
exec:TReallocPool()
is the same on all platforms, while the efficiency
of exec:TRealloc()
with a TNULL
memory manager can significantly
differ.
TAllocPool()
mem = TAllocPool(pool, size) TAPTR struct TMemPool* TSIZE
This function allocates a block of memory from a pool. A Pointer
to the allocated block of memory is returned, or TNULL
if the
request cannot be satisfied.
mem
- Pointer to a block of memory, or TNULL
if out of memory
pool
- Pointer to a pool created with exec:TCreatePool()
size
- Size of the allocation [bytes]
TFreePool()
TFreePool(pool, mem, size) struct TMemPool* TUINT TSIZE
Return a block of memory to the pool from which it was allocated.
pool
- Pointer to the pool the allocation was made from
mem
- Block of memory to be freed
size
- Size of the allocation
TReallocPool()
newmem = TReallocPool(pool, oldmem, oldsize, newsize) TAPTR struct TMemPool* TAPTR TUINT TSIZE
Resize a block of memory that has been allocated from a pool. If
newsize
is 0
then the allocation will be freed, and the result
will be TNULL
. If oldmem
is TNULL
and oldsize
is 0
,
a new block will be allocated.
newmem
- Pointer to resized block, or TNULL
if failed
pool
- Pointer to the pool the allocation was made from
oldmem
- Pointer to memory allocated
oldsize
- Previous size of the allocation
newsize
- New size for the allocation
exec:TAllocPool()
, exec:TFreePool()
, exec:TCreatePool()
TPutIO()
TPutIO(ioreq) struct TIORequest*
This function puts an I/O request to the device or handler
specified in the ioreq->io_Device
field.
TPutIO()
clears the TIOF_QUICK flag from the ioreq->io_Flags
field, indicating that it prefers asynchronous execution, and
forwards the request through the BeginIO
-vector of the device.
Whether or not the request will be executed asynchronously remains
transparent to the caller. After the request has been processed,
it will return to the replyport specified in ioreq->io_ReplyPort
and cause the replyport's signal to show up in the caller's task.
Always use exec:TWaitIO()
to synchronize on completion of an I/O
request and its removal from the replyport queue.
iorequest
- I/O request message to be processed
TWaitIO()
error = TWaitIO(ioreq) TINT struct TIORequest*
This function waits for an I/O request to complete and unlinks it
from its ioreq->io_ReplyPort
. If the request has already finished
or was processed synchronously then TWaitIO()
drops through
immediately.
error
- Contents of the iorequest's io_Error
field. A return
value of 0
indicates success.
iorequest
- I/O request message to be processed.
TDoIO()
error = TDoIO(ioreq) TINT struct TIORequest*
This function performs an I/O request and waits for completion.
TDoIO()
indicates that it prefers synchronous execution by
setting the TIOF_QUICK
flag in the ioreq->io_Flags
field
before the request is forwarded through the BeginIO
-vector of the
device.
error
- Contents of the iorequest's io_Error
field. A return
value of zero indicates success.
iorequest
- I/O request message to be processed.
TCheckIO()
complete = TCheckIO(ioreq) TBOOL struct TIORequest*
This function tests if an I/O request has been completed and returns its status to the caller.
Note that a finished I/O request still needs to be removed
from the replyport's queue using exec:TWaitIO()
.
complete
- Boolean
iorequest
- I/O request message to be processed
exec:TPutIO()
, exec:TWaitIO()
, exec:TDoIO()
, exec:TAbortIO()
,
exec:TPutMsg()
TAbortIO()
error = TAbortIO(ioreq) TINT struct TIORequest*
Ask a device to abort an I/O request that has been initiated
using exec:TPutIO()
. Note that abortion is a service that
may or may not be granted by the addressed device or handler.
You must in no way rely on successful abortion, and you still
have to synchronize on the I/O request properly using exec:TWaitIO()
.
error
0
if the request for abortion was sent-1
if the request is still pending
iorequest
- I/O request message to be processed
exec:TPutIO()
, exec:TWaitIO()
, exec:TDoIO()
, exec:TCheckIO()
,
exec:TPutMsg()
TAllocTimeRequest()
timereq = TAllocTimeRequest(tags) struct TTimeRequest* TTAGITEM*
This function opens the timer device and returns a pointer to a time request.
Each time request allocated by this function must be freed using
exec:TFreeTimeRequest()
.
timereq
- Pointer to a time request structure, or TNULL
if
the device open or allocation failed
tags
- Pointer to an array of tag items (none defined yet)
TFreeTimeRequest()
TFreeTimeRequest(timereq) struct TTimeRequest*
This function frees a time request that was allocated with
exec:TAllocTimeRequest()
.
timereq
- Pointer to a time request
TGetSystemTime()
TGetSystemTime(timep) TTIME*
This function queries a (relative) system time and inserts it into
the time structure being pointed to by timep
.
timep
- Pointer to a time structure to be filled
TTIME
is a relative quantity.
It might appear as if the fields filled in by this function could
in some way reflect an absolute time or date, but this would be
entirely misleading as the base for a TTIME
structure can differ
among different hosts. For getting an absolute date and time use
the more expensive date functions.
exec:TGetUniversalDate()
, exec:TGetLocalDate()
TGetUniversalDate()
error = TGetUniversalDate(datep) TINT TDATE*
This function queries the system's absolute time and date in UTC
(Universal Time Coordinated) and inserts it into the TDATE
being
pointed to by datep
.
error
- Error value, indicating
0
- for success-1
- invalid arguments-2
- no date resource available
datep
- Pointer to a TDATE
receiving the date and time
TTIME
structure, which is better accessible by applications and requires
less complex internal calculations. See exec:TGetSystemTime()
and
teklib:TSubTime()
for details.
exec:TGetLocalDate()
, exec:TGetSystemTime()
TGetLocalDate()
error = TGetLocalDate(datep) TINT TDATE*
This function queries the system's local time and date and inserts it
into the TDATE
being pointed to by datep
.
error
- Error value, indicating
0
- for success-1
- invalid arguments-2
- no date resource available
datep
- Pointer to a TDATE
receiving the date and time
TWaitTime()
signals = TWaitTime(timeout, sigmask) TUINT TTIME* TUINT
Suspend the current task to wait for a set of signals or for a
timeout. Any signals causing this function to return will be
returned to the caller and cleared from the task's signal state.
If a timeout causes the return then the return value is 0
. If
timeout is TNULL
then this function is equivalent to exec:TWait()
.
timeout
- Pointer to a TTIME
structure
sigmask
- Set of signals to wait for
signals
- Signals that caused returning, or 0
if a timeout
occured
TWaitDate()
signals = TWaitDate(datep, sigmask) TUINT TDATE* TUINT
Suspend the current task to wait for a set of signals or for an
absolute date. Any signals causing this function to return will be
returned to the caller and cleared from the task's signal state.
If an expiring date causes the return then this function returns 0
.
If datep
is TNULL
then this function is equivalent to exec:TWait()
.
absdate
- Pointer to a TDATE structure
sigmask
- Set of signals to wait for
signals
- Signals that caused returning, or 0
if a timeout
occured
TScanModules()
handle = TScanModules(tags) struct THandle* TTAGITEM*
This function searches for modules that are available to TEKlib's module
open function and, if successful, returns a handle that can be queried
using teklib:TGetNextEntry()
.
Each invocation of teklib:TGetNextEntry()
on the resulting handle returns
a pointer to a taglist, or TNULL
when there are no more entries
available. Possible tags in this taglist, as currently defined, are:
TExec_ModuleName, (TSTRPTR)
- Name of a module that would be available toexec:TOpenModule()
.
When you are done scanning for modules, the handle should be destroyed
with teklib:TDestroy()
.
handle
- A handle that can be passed to teklib:TGetNextEntry()
,
or TNULL
if scanning failed.
tags
- Pointer to an array of tag items:
TExec_ModulePrefix (TSTRPTR)
- Pointer to a prefix string. If specified, only modules whose names begin with this prefix will be returned. Default:TNULL
Scan the system for TEKlib modules with the prefix "io"
:
TTAGITEM tags[2]; tags[0].tti_Tag = TExec_ModulePrefix; tags[0].tti_Value = (TTAG) "io"; tags[1].tti_Tag = TTAG_DONE; struct THandle *handle = TScanModules(tags); if (handle) { TTAGITEM *entry; while ((entry = TGetNextEntry(handle))) printf("%s\n", (TSTRPTR) TGetTag(entry, TExec_ModuleName, TNULL)); } TDestroy(handle);
util:TBSwap16()
- Swap bytes in a 16bit integer
util:TBSwap32()
- Swap bytes in a 32bit integer
util:TDateToDMY()
- Convert a date to day, month, year
util:TDMYToYDay()
- Convert a date to a year day
util:TGetArgC()
- Get application's argument count
util:TGetArgs()
- Return an application's arguments as a single string
util:TGetArgV()
- Get application's argument vector
util:TGetRand()
- Get pseudo random number
util:TGetWeekDay()
- Get day of week from day, month and year
util:TGetWeekNumber()
- Get week of year from day, month and year
util:THeapSort()
- Sort a field via reference array and comparison hook
util:THToNL()
- Convert 32bit integer from/to network byte order
util:THToNS()
- Convert 16bit integer from/to network byte order
util:TIsBigEndian()
- Test if host is big endian
util:TIsLeapYear()
- Check if a year is a leap year
util:TIsValidDate()
- Check if a date is valid
util:TMYToDay()
- Convert month, year to days since 1.1.1601
util:TPackDate()
- Pack a datebox structure to a TEKlib date
util:TParseArgs()
- Parse an argument string
util:TParseArgV()
- Parse argument vector
util:TSeekList()
- Seek in a list
util:TSetRetVal()
- Set application's return value
util:TStrDup()
- Allocate memory for and copy a string
util:TStrNDup()
- Allocate memory for and copy a string, length-limited
util:TUnpackDate()
- Unpack a TEKlib date to a datebox structure
util:TYDayToDM()
- Convert year day to day and month
TGetArgC()
argc = TGetArgC() TINT
Return an application's argument count.
argc
- Number of arguments passd to the application
The result will be 0
if an argument vector is unsupported
by the application startup.
util:TGetArgV()
, util:TSetRetVal()
TGetArgV()
argv = TGetArgV() TSTRPTR*
Return an application's array of arguments.
argv
- Pointer to aTNULL
-terminated array of string pointers
The argument vector contains the arguments supplied to the application,
or TNULL
if an argument vector is unsupported by the application
startup.
If an argv
vector is available, then it will always be terminated
with an additional array element containing TNULL
.
util:TGetArgC()
, util:TSetRetVal()
TSetRetVal()
success = TSetRetVal(value) TBOOL TINT
Set an application-wide return value. If supported by the application's entry point, the value will be returned to the hosting environment.
success
-TTRUE
if setting the return value succeeded.
value
- Return value to set in the application
util:TGetArgC()
, util:TGetArgV()
THeapSort()
success = THeapSort(refarray, length, hook) TBOOL TTAG* TUINT struct THook*
Using the Heapsort algorithm, sort data of the given length, via a reference array and comparison hook. This layout allows you to sort any kind of data structure, including arrays of any type, and even lists. The reference array will usually contain indices or pointers.
success
- Boolean
Possible reasons for failure are: No comparison function or reference array given or less than two entries to sort.
refarray
- Array of references, i.e. indices or pointerslength
- Number of entries to be sortedhook
- Comparison hook
The comparison hook function must return a value less than zero indicating "ref1 less than ref2", a value greater zero indicating "ref1 greater than ref2", and zero for "ref1 equal to ref2". It expects a pointer to the following data structure as its object:
struct CmpData { TTAG ref1; TTAG ref2; };
The Heapsort algorithm is slower than Quicksort, but it has no stack impact, and its performance is insensitive to the initial array order.
TSeekList()
newnode = TSeekNode(node, steps) struct TNode* struct TNode* TINTPTR
Seek in a doubly linked list by a given number of steps either
forward (steps > 0) or backward (steps < 0), and return the
node reached, or TNULL
if seeked past end or before start of
the list. If steps is zero, node is returned.
newnode
- Node reached, orTNULL
node
- Starting nodesteps
- Number of steps to seek
TIsBigEndian()
isbig = TIsBigEndian() TBOOL
Determine the host's endianness. If the host is a big endian
architecture, a 32bit register containing 0x11223344
stored in
memory would yield the byte sequence 0x11
, 0x22
, 0x33
,
0x44
. On such an architecture, this function returns TTRUE
. On
a little endian architecture, the byte sequence would be 0x44
,
0x33
, 0x22
, 0x11
, and this function returned TFALSE
.
isbig
- Boolean.TTRUE
if the host is big endian.
util:THToNL()
, util:THToNS()
, util:TBSwap16()
, util:TBSwap32()
TBSwap16()
TBSwap16(valp) TUINT16*
Reverse the order of the two bytes in memory to which
valp
points.
valp
- Pointer to a 16bit integer to swap
util:THToNL()
, util:TBSwap32()
, util:TIsBigEndian()
TBSwap32()
TBSwap32(valp) TUINT*
Reverse the order of the four bytes in memory to which
valp
points.
valp
- Pointer to a 32bit integer to swap
util:THToNL()
, util:TBSwap16()
, util:TIsBigEndian()
TStrDup()
dup = TStrDup(memmanager, string) TSTRPTR struct TMemManager* TSTRPTR
Allocate memory for, copy, and return a pointer to a duplicate of
a string. If string is TNULL
, a string will be allocated containing
only a string's trailing zero-byte.
dup
- A copy of the string, orTNULL
if out of memory.
memmanager
- Memory manager to allocate from, orTNULL
string
- String to be duplicated
The resulting string must be freed using
exec:TFree()
.
TStrNDup()
dup = TStrNDup(memmanager, string, maxlen) TSTRPTR struct TMemManager* TSTRPTR TSIZE
Allocate memory for, copy, and return a pointer to a duplicate of
a string. If string is TNULL
, a string will be allocated containing
only a string's trailing zero-byte. The duplicate will be limited to
a maximum of maxlen characters.
dup
- A copy of the string, orTNULL
if out of memory.
memmanager
- Memory manager to allocate from, orTNULL
string
- String to be duplicatedmaxlen
- Maximum number of bytes to duplicate
The resulting string must be freed using
exec:TFree()
.
TGetRand()
num = TGetRand(seed) TUINT TUINT
From a seeding previous random number, generate a pseudo random
number in the range from 0 to 2147483647 (hexadecimal
0x7fffffff
).
num
- Pseudo random number
TParseArgV()
handle = TParseArgV(template, argv, args) struct THandle* TSTRPTR TSTRPTR* TTAG*
Parse an array of string pointers into an arguments array, according to a format template.
The array of string pointers is here referred to as 'argv', because
a typical use of this function is to parse an application's
commandline arguments. Note, however, that it can be applied to any
other TNULL
-terminated array of string pointers as well.
The template string specifies the expected format. Options in the template are separated by commas. Each argument consists of a name, an optional alias, and an optional set of qualifiers. Example:
-s=SOURCE/A/M,-d=DEST/A/K
This format would require one or more source arguments and a single destination argument. Neither can be omitted. The SOURCE keyword (or its alias -s) does not need to appear in the command line. The DEST keyword (or its alias -d) must appear in the commandline to be valid. This is how the template would be interpreted:
SOURCE one two three DEST foo | Valid |
DEST foo -s one | Valid |
DEST foo | Rejected - source missing |
one two three foo | Rejected - keyword missing |
one two dest foo | Valid - keywords are not case-sensitive |
one two three -d foo four | Valid - "four" would be added to SOURCE |
An option without qualifiers represents a string argument. If present, a pointer to the string will be placed into the respective entry in the args array. Qualifiers are:
/S
- Switch. This is considered a boolean variable. When this
option is present, the value TTRUE will be written into the
respective entry in the args array.
/N
- This argument is considered an integer in decimal notation.
When present, a pointer to a 32bit signed integer will be placed
into the respective entry in the args array. A pointer to the
number is inserted (not the number itself) so that the caller can
determine whether the argument was specified.
/K
- Keyword. The option will not be accepted unless the keyword
appears in the argv vector.
/A
- Required. This argument cannot be omitted. If not present,
an error is returned.
/M
- Multiple strings. Any number of strings will be accepted for
this option. Not more than one /M modifier should appear in a
template. Any arguments that cannot be assigned to other options
will be added to this option. The respective entry in the args
array will be a pointer to a TNULL-terminated array of string
pointers.
If parsing is successful, this function returns a handle. When you
are finished processing the arguments, this handle must be passed
to teklib:TDestroy()
to free all associated memory.
template
- Format stringargv
- Array of string pointers to be parsedargs
- Pointer to an array of tags to be filled with arguments
handle
- argument handle
The argument handle will be TNULL if parsing failed. When the application
has finished processing the arguments, the handle must be passed to
teklib:TDestroy()
for freeing all associated memory.
/* Template string */ TSTRPTR template = "-f=FROM/A,-c=CONTEXT/K,-r=RECURSE/S,-h=?/S"; /* Initialize args array to defaults */ TTAG args[4] = {TNULL, (TTAG) "linux_gcc", TFALSE, TFALSE}; /* Get argv vector */ TSTRPTR *argv = TGetArgV(); /* Pass argv + 1 so the program name argv[0] is excluded */ struct THandle *argh = TParseArgV(template, argv + 1, args); if (argh && !args[3]) { /* Use the arguments here. Do not destroy the handle yet! */ } else { /* Either parsing failed or the "help" option was given */ printusage(); } /* Clean up */ TDestroy(argh);
THToNL()
val = THToNL(val) TUINT TUINT
If the software is running on a little-endian architecture, this function will byte-swap the value. On a big-endian architecture, it will be returned unmodified. This will convert the specified value from/to network byte order on any architecture.
val
- 32bit integer, byte-swapped if running on little-endian
val
- 32bit integer
util:THToNS()
, util:TIsBigEndian()
, util:TBSwap32()
THToNS()
val = THToNS(val) TUINT16 TUINT16
If the software is running on a little-endian architecture, this function will byte-swap the value. On a big-endian architecture, it will be returned unmodified. This will convert the specified value from/to network byte order on any architecture.
val
- 16bit integer, byte-swapped if running on little-endian
val
- 16bit integer
util:THToNL()
, util:TIsBigEndian()
, util:TBSwap16()
TParseArgs()
handle = TParseArgs(template, argstring, argarray) struct THandle* TSTRPTR TSTRPTR TTAG*
Parse an argument string into an arguments array, according to a format template.
The template string specifies the expected format. Options in the template are separated by commas. Each argument consists of a name, an optional alias, and an optional set of qualifiers.
If parsing is successful, then this function returns a handle. When
you are finished processing the arguments, this handle must be
passed to teklib:TDestroy()
for freeing all associated memory.
See util:TParseArgV()
for a detailed description of the expected format.
handle
- Argument handle, orTNULL
if parsing failed
template
- Format stringargv
- Array of string pointers to be parsedargs
- Pointer to an array of tags to be filled
util:TGetArgs()
, util:TParseArgV()
TGetArgs()
args = TGetArgs() TSTRPTR
Return an application's argument vector (argv
) in a single string,
with the individual items being seperated with spaces.
args
- application arguments
TIsLeapYear()
isleapyear = TIsLeapYear(year) TBOOL TUINT
Check if year is a leap year.
isleapyear
- TTRUE if leap year, TFALSE otherweise
year
- Year to check
TIsValidDate()
valid = TIsValidDate(day, month, year) TBOOL TUINT TUINT TUINT
Check if the given combination from day, month, year is a
valid date, e.g. 29, 2, 2003 would be an invalid date, and
this function would return TFALSE
.
valid
- Boolean
day, month, year
- Date
TYDayToDM()
success = TYDayToDM(yearday, year, pday, pmonth) TBOOL TUINT TUINT TUINT* TUINT*
Convert a year and yearday to a month's day and month of the given year.
yearday
- Daynumber in the respective yearyear
- The yearpday
- Pointer to an integer receiving the day (may beTNULL
)pmonth
- Pointer to an integer receiving the month (may beTNULL
)
TDMYToYDay()
yday = TDMYToYDay(day, month, year) TUINT TUINT TUINT TUINT
Convert a date in the format day, month, year to yearday of the given year.
yday
- Day of the year
day, month, year
- Date
TMYToDay()
day = TMYToDay(month, year) TUINT TUINT TUINT
From the given month and year, calculate the number of days since 1-Jan-1601.
day
- Day number since 1.1.1601
month
- Month to convertyear
- Year to convert
TDateToDMY()
TDateToDMY(date, pday, pmonth, pyear, ptime) TDATE* TUINT* TUINT* TUINT* TTIME*
This function converts a date to a day, month, year, and the remaining fraction of the day into a time structure.
date
- TEKlib Datepday
- Pointer to an integer for day (may beTNULL
)pmonth
- Pointer to an integer for month (may beTNULL
)pyear
- Pointer to an integer for year (may beTNULL
)ptime
- Pointer to a TEKlib time (may beTNULL
)
TGetWeekDay()
wday = TGetWeekDay(day, month, year) TUINT TUINT TUINT TUINT
This function gets the week's day number (0, sunday - 6, saturday) from a date given by day, month, year.
wday
- Day of week
day
- Daymonth
- Monthyear
- Year
TGetWeekNumber()
wnumber = TGetWeekDay(day, month, year) TUINT TUINT TUINT TUINT
This function gets the year's week number from a date given by day, month, year.
wnumber
- Week of year
day
- Daymonth
- Monthyear
- Year
TPackDate()
success = TPackDate(datebox, tdate) TBOOL struct TDateBox* TDATE*
Convert a datebox structure to a date. All fields with a
corresponding bit in datebox->tdb_Fields
will be possibly
taken into account. Fields required are TDB_YEAR
and either
TDB_MONTH
, TDB_DAY
or TDTB_YDAY
. More fields like
TDB_HOUR
, TDB_MINUTE
etc. will be incorporated to the
resulting date as well, if they are present. If not enough
relevant fields are provided then this function returns TFALSE
.
See util:TUnpackDate()
for a description of the flags in
datebox->tdb_Fields
.
success
-TTRUE
if conversion succeeded
datebox
- Pointer to a source datebox structuretdate
- Pointer to a destinationTDATE
TUnpackDate()
TUnpackDate(date, datebox, fields) TDATE* struct TDateBox* TUINT16
Convert a date to a datebox structure. At least the fields marked in the fields argument will be inserted to the resulting datebox structure.
Specific combinations of date fields may be sufficient for
a given purpose, like TDB_DAY|TDB_MONTH|TDB_YEAR
or
TDB_YDAY|TDB_YEAR|TDB_SEC
. If you want to receive all
fields, pass TDB_ALL
in the fields argument. The fields
actually being inserted by this function (which can be more
than requested) will be flagged as correponding bits in
datebox->tdb_Fields
.
date
- pointer to a source datedatebox
- pointer to a TDateBox structure to be filled infields
- Fields to be inserted into the datebox structure. Valid flag fields:
Flag Description corresponds to TDB_YEAR year datebox->tdb_Year TDB_YDAY day of year datebox->tdb_YDay TDB_MONTH month of year datebox->tdb_Month TDB_WEEK week of year datebox->tdb_Week TDB_WDAY day of week datebox->tdb_WDay TDB_DAY day of month datebox->tdb_Day TDB_HOUR hour of day datebox->tdb_Hour TDB_MINUTE minute of hour datebox->tdb_Minute TDB_SEC second of minute datebox->tdb_Sec TDB_USEC 1/1000000th sec datebox->tdb_USec TDB_ALL all of the above all of the above