Copyright (c) Hyperion Entertainment and contributors.

Difference between revisions of "Utility Library"

From AmigaOS Documentation Wiki
Jump to navigation Jump to search
Line 3: Line 3:
   
 
Utility library is the home for all the OS functions which don't fit in the other libraries. Among the calls in utility library are calls to manage tags and tag lists, callback hooks, and some generic 32-bit math functions, all discussed below.
 
Utility library is the home for all the OS functions which don't fit in the other libraries. Among the calls in utility library are calls to manage tags and tag lists, callback hooks, and some generic 32-bit math functions, all discussed below.
 
== Callback Hooks ==
 
 
The callback feature provides a standard means for applications to extend the functionality of libraries, devices, and applications. This standard makes it easy for the operating system to use custom modules from different high level programming languages as part of the operating system. For example, the layers library, which takes care of treating a display as a series of layered regions, allows an application to attach a pattern function to a display layer. Instead of filling in the background of a layer with the background color, the layers library calls the custom pattern function which fills in the layer display with a custom background pattern.
 
 
=== Callback Hook Structure and Function ===
 
 
An application passes a custom function in the form of a callback Hook (from <utility/hooks.h>):
 
 
<syntaxhighlight>
 
struct Hook
 
{
 
struct MinNode h_MinNode;
 
ULONG (*h_Entry)(); /* function entry point */
 
ULONG (*h_SubEntry)(); /* secondary function entry point (not usually used) */
 
VOID *h_Data; /* owner specific */
 
};
 
</syntaxhighlight>
 
 
; h_MinNode
 
: This field is reserved for use by the module that will call the Hook.
 
 
; h_Entry
 
: This is the address of the callback function. Since AmigaOS 4.0, all callbacks adhere to the PowerPC SysV ABI which is stack based and therefore the order of the parameters is important. When AmigaOS ran only on 68000 based CPUs, this entry would point to a hook stub which would take the arguments from 68000 registers A0, A1, and A2, push them on the stack and finally call h_SubEntry.
 
 
; h_SubEntry
 
: This is the address of the secondary function entry point. It should only used when emulating 68000 code.
 
 
; h_Data
 
: This field is for the application to use. It could point to a global storage structure that the callback function utilizes.
 
 
There is only one function defined in utility library that relates to callback hooks:
 
 
<syntaxhighlight>
 
uint32 CallHookPkt(struct Hook *hook, APTR object, APTR paramPkt);
 
</syntaxhighlight>
 
 
CallHookPkt will always ensure the correct procedure is used to invoke a callback. If the callback points to PowerPC code, it will be called directly. If the callback points to 68000 code, it will invoke the emulator and take the appropriate action.
 
 
=== Simple Callback Hook Usage ===
 
 
A Hook function accepts the following three parameters in the order specified:
 
 
# Pointer to the Hook structure.
 
# Pointer to an object to manipulate. The object is context specific.
 
# Pointer to a message packet. This is also context specific.
 
 
For a callback function written in C, the parameters must appear in this order:
 
 
<syntaxhighlight>
 
myCallbackFunction(Pointer to Hook, // A0 in 68000
 
Pointer to Object, // A2 in 68000
 
Pointer to message); // A1 in 68000
 
</syntaxhighlight>
 
 
A callback function is executed on the context of the module that invoked it. This usually means that callback functions cannot call functions that need to look at environment specific data. For example, Printf() needs to look at the current process's input and output stream. Entities like Intuition have no input and output stream. To find out which context your callback is running on use the FindTask() function from Exec.
 
 
The following is a simple function that can be used in a callback hook which indicates which context it is running on.
 
 
<syntaxhighlight>
 
uint32 MyFunction (struct Hook *h, VOID *o, VOID *msg)
 
{
 
struct Task *task = IExec->FindTask(0);
 
 
/* Debugging function to send a string to the serial port */
 
IExec->DebugPrintF("MyFunction() running on Task %s\n",
 
(task->tc_Node.ln_Name == NULL) ? "NoName" : task->tc_Node.ln_Name);
 
 
return 1;
 
}
 
</syntaxhighlight>
 
 
The next step is to initialize the Hook for use. This basically means that the fields of the Hook structure must be filled with appropriate values. There are two ways to accomplish this. Either use the AllocSysObject() function with an object type of ASOT_HOOK or declare the hook statically and manually initialize the fields.
 
 
The following example shows how to allocate a Hook structure dynamically:
 
 
<syntaxhighlight>
 
struct Hook *hook = IExec->AllocSysObjectTags(ASOT_HOOK,
 
ASOHOOK_Entry, func,
 
ASOHOOK_Data, data,
 
TAG_END);
 
</syntaxhighlight>
 
 
The following simple function initializes a static Hook structure.
 
 
<syntaxhighlight>
 
/* This simple function is used to initialize a Hook */
 
VOID InitHook (struct Hook *h, uint32 (*func)(), VOID *data)
 
{
 
/* Make sure a pointer was passed */
 
if (h != NULL)
 
{
 
/* Fill in the hook fields */
 
h->h_Entry = func;
 
h->h_SubEntry = NULL;
 
h->h_Data = data;
 
}
 
}
 
</syntaxhighlight>
 
 
The following is a simple example of a callback hook function.
 
 
<syntaxhighlight>
 
// hooks1.c
 
 
#include <exec/types.h>
 
#include <exec/libraries.h>
 
#include <utility/hooks.h>
 
#include <dos.h>
 
 
// Note the newlib startup code opens these libraries.
 
#include <proto/exec.h>
 
#include <proto/utility.h>
 
 
/* This function only prints out a message indicating that we are
 
* inside the callback function.
 
*/
 
uint32 MyFunction (struct Hook *h, VOID *o, VOID *msg)
 
{
 
/* Debugging function to send a string to the serial port */
 
IExec->DebugPrintF("Inside MyFunction()\n");
 
 
return (1);
 
}
 
 
int main()
 
{
 
struct Hook *h = IExec->AllocSysObjectTags(ASOT_HOOK,
 
ASOHOOK_Entry, MyFunction,
 
TAG_END);
 
 
if (h != NULL)
 
{
 
/* Use the utility library function to invoke the Hook */
 
IUtility->CallHookPkt (h, NULL, NULL);
 
 
IExec->FreeSysObject(ASOT_HOOK, h);
 
}
 
}
 
</syntaxhighlight>
 
   
 
== String Functions ==
 
== String Functions ==

Revision as of 23:09, 26 March 2014

WIP.png This page is currently being updated to AmigaOS 4.x. Some of the information contained here may not yet be applicable in part or totally.

Utility Library

Utility library is the home for all the OS functions which don't fit in the other libraries. Among the calls in utility library are calls to manage tags and tag lists, callback hooks, and some generic 32-bit math functions, all discussed below.

String Functions

Regular String Functions

These functions perform operations on strings with no regard for localization.

Currently implemented are:

Strlcat() Length limited string concatenation.
Strlcpy() Length limited string copy.
VASPrintf Formatted output conversion with result are stored in dynamically allocated buffer.
VSNPrintf Length limited formatted output conversion.

International String Functions

When the localization library is opened, these functions will be replaced by ones which will take the locale as defined by the user into account. This means that the compare order may change according to the locale, so care should be taken not to rely on obtaining specific compare sequences.

Currently implemented are:

Stricmp() Compare string case-insensitive.
Strnicmp() Compare string case-insensitive, with a specified length.
ToLower() Convert a character to lower case.
ToUpper() Convert a character to upper case.

These functions operate in the same manner as their ANSI C equivalents, for the most part. For more information, see the "Utility Library" Autodocs in the SDK. Here is a simple example of the usage of the international string functions.

/*
** istr.c
*/
 
#include <exec/types.h>
 
#include <proto/exec.h>
#include <proto/utility.h>
 
int main()
{
    CONST_STRPTR butter = "Bøtervløøt";
    CONST_STRPTR bread = "Knåckerbrøt";
 
    int32 result = IUtility->Stricmp(butter, bread);
 
    IDOS->Printf("comparing %s with %s yields %ld\n", butter, bread, result );
 
    result = IUtility->Strnicmp(bread, butter, strlen(bread));
 
    IDOS->Printf("comparing (with length) %s with %s yields %ld\n", bread, butter, result );
 
    uint8 ch1 = IUtility->ToUpper(0xE6); /* ASCII character 230 ae ligature */
    uint8 ch2 = IUtility->ToLower(0xD0); /* ASCII character 208 Icelandic Eth */
 
    IDOS->Printf("Chars %lc %lc\n", ch1, ch2);
 
    return 0;
}

Date Functions

To ease date-related calculations, the utility library has some functions to convert a date, specified in a ClockData structure, in the number of seconds since 00:00:00 01-Jan-78 and vice versa.

To indicate the date, the ClockData structure (in <utility/date.h>) is used.

struct ClockData
{
    UWORD sec;     /* seconds (0 - 59) */
    UWORD min;     /* minutes (0 - 59) */
    UWORD hour;    /* hour (0 - 23) */
    UWORD mday;    /* day of the month (1 - 31) */
    UWORD month;   /* month of the year (1 - 12) */
    UWORD year;    /* 1978 - */
    UWORD wday;    /* day of the week (0 - 6, where 0 is Sunday) */
};

The following functions are available to operate on ClockData:

Utility Library Date Functions
Amiga2Date() Calculate the date from the specified timestamp (in seconds).
CheckDate() Check the legality of a date.
Date2Amiga() Calculate the timestamp from the specified date.

Amiga2Date() takes a number of seconds from 01-Jan-78 as argument and fills in the supplied ClockData structure with the date and time.

CheckDate() checks if the supplied ClockData structure is valid, and returns the number of seconds from 01-Jan-78 if it is. Note that this function currently does not take the supplied day of the week in account.

Date2Amiga() takes a ClockData structure as argument and returns the number of seconds since 01-Jan-78. The supplied ClockData structure must be valid, since no checking is done.

The following example shows various uses of the utility library date functions.

// a2d.c
#include <exec/types.h>
#include <exec/memory.h>
#include <dos/datetime.h>
#include <devices/timer.h>
 
// Note these three libraries are opened by newlib startup code.
#include <proto/exec.h>
#include <proto/dos.h>
#include <proto/utility.h>
 
#include <proto/timer.h>
 
struct TimerIFace *ITimer = NULL;
 
int main()
{
  struct timerequest *tr = IExec->AllocSysObjectTags(ASOT_IOREQUEST,
    ASOIOR_Size, sizeof(struct TimeRequest),
    ASOIOR_ReplyPort, NULL,
    TAG_END);
 
  if (tr != NULL)
  {
    if (!(IExec->OpenDevice("timer.device", UNIT_VBLANK, (struct IORequest *)tr, 0) ))
    {
      struct Library *TimerBase = tr->tr_node.io_Device;
      ITimer = (struct TimerIFace*)IExec->GetInterface(TimerBase, "main", 1, NULL);
 
      if (ITimer != NULL)
      {
        struct TimeVal tv;
        ITimer->GetSysTime(&tv);
 
        IDOS->Printf("GetSysTime():\t%d %d\n", tv.Seconds, tv.Microseconds);
 
        struct ClockData clockdata;
        IUtility->Amiga2Date(tv.Seconds, &clockdata);
 
        IDOS->Printf("Amiga2Date():  sec %d min %d hour %d\n",
          clockdata.sec, clockdata.min, clockdata.hour);
 
        IDOS->Printf("               mday %d month %d year %d wday %d\n",
          clockdata.mday, clockdata.month, clockdata.year, clockdata.wday);
 
        int32 seconds = IUtility->CheckDate(&clockdata);
 
        IDOS->Printf("CheckDate():\t%ld\n", seconds);
 
        seconds = IUtility->Date2Amiga(&clockdata);
 
        IDOS->Printf("Date2Amiga():\t%ld\n", seconds);
 
        IEXec->DropInterface((struct Interface*)ITimer);
      }
 
      IExec->CloseDevice((struct IORequest *)tr);
    }
 
    IExec->FreeSysObject(ASOT_IOREQUEST, tr);
  }
 
  return RETURN_OK;
}

Named Objects

AddNamedObject() Add a named object to a namespace.
AllocNamedObject() Allocate a named object.
AttemptRemNamedObject() Attempt to remove a named object.
FindNamedObject() Find the next named object (case sensitive).
FreeNamedObject() Frees a named object.
NamedObjectName() Return the name of a named object.
ReleaseNamedObject() Release usage of a named object.
RemNamedObject() Remove a named object from any namespace.

Insert documentation here.

Data Structures

Splay Trees

Splay trees are a form of binary tree which organizes itself in response to insertions and searches. Whenever a search finds a specific tree node, that node is "pulled up" into the tree root, and the tree is subsequently reorganized. This reorganization is called "splaying" and has the effect of making the tree flatter, shortening the distances between the root and leaf nodes. Also, more frequently-used nodes will move more closely to the root of the tree during each splay operation. The more splay operations are performed, the more closely the tree will represent the frequency of the node accesses, and will eventually place the most frequently-used nodes close to the root of the tree. This self-organization makes splay trees well-suited for use in caches or dictionaries. Because search operations will modify the splay tree, you should always use an arbitration mechanism such as a Mutex if you share the same splay tree with several Tasks or Processes.

See Wikipedia for more generic information about splay trees.

CreateSplayTree() Allocate a splay tree data structure.
DeleteSplayTree() Free a splay tree and all its nodes.
FindSplayNode() Search for a key in a splay tree.
InsertSplayNode() Insert a new key into a splay tree.
RemoveSplayNode() Remove a node from a splay tree.

Skip Lists

Skip lists combine linked lists with a look-ahead data structure which makes search and insertion operations efficient. You can add data in any particular order to the skip list, and the list will always take care of keeping that data stored in a specific order. The effort spent to maintain this order is small and grows slowly the more list items are added. Traversing the list is very fast and will always return the list items in sorted order. Retrieving specific list items is very efficient, too. Skip lists are useful if you need to be able to retrieve list items in a sorted order at any time while you are building the list. The drawback of skip lists is that the amount of memory required to maintain the list grows faster than the number of list items added.

See Wikipedia for more generic information about skip lists.

CreateSkipList() Allocate a skip list data structure.
DeleteSkipList() Free a skip list and all its nodes.
FindSkipNode() Search for a key in a skip list.
GetFirstSkipNode() Get a pointer to the first node of a skip list.
GetNextSkipNode() Get a pointer to the following node in a skip list.
InsertSkipNode() Insert a new key into a skip list.
RemoveSkipNode() Remove a node from a skip list.

Function Reference

The tables which follow contain breif descriptions of the functions inside the utility library. See the SDK for details on each function call.

Tag Function Reference

The following are brief descriptions of the utility library functions which pertain to tags and tag lusts.

Function Description
AllocSysObjectTags(ASOT_TAGLIST) Allocate a TagItem array (or chain).
FreeSysObject(ASOT_TAGLIST) Frees allocated TagItem lists.
CloneTagItems() Copies a TagItem list.
RefreshTagItemClone() Rejuvenates a clone from the original.
FindTagItem() Scans TagItem list for a tag.
GetTagData() Obtain data corresponding to tag.
NextTagItem() Iterate TagItem lists.
TagInArray() Check if a tag value appears in a Tag array.
FilterTagChanges() Eliminate TagItems which specify no change.
FilterTagItems() Remove selected items from a TagItem list.
MapTags() Convert ti_Tag values in a list via map pairing.
PackBoolTags() Builds a "Flag" word from a TagItem list.

Callback Hook Function Reference

The following are brief descriptions of the utility library functions which pertain to callback hooks.

Function Description
CallHookPkt() Call a standard callback Hook function.

International String Function Reference

The following are brief descriptions of the utility library functions which pertain to string operations using the international ASCII character set.

Function Description
Stricmp() Compare strings, case-insensitive.
Strnicmp() Compare strings, case-insensitive, with specified length.
ToLower() Convert a character to lower case.
ToUpper() Convert a character to upper case.

Date Function Reference

The following are brief descriptions of the utility library functions which pertain to date conversion.

Function Description
CheckDate() Check the legality of a date.
Amiga2Date() Calculate the date from a specified timestamp.
Date2Amiga() Calculate the timestamp from a specified date.