Chapter 2. RWBTree - RWCRExpr

RWBTree

RWBTree ->- RWCollection ->- RWCollectable 

Synopsis

#include <rw/btree.h>
 
RWBTree a;

Description

Class RWBTree represents a group of ordered elements, not accessible by an external key. Duplicates are not allowed. An object stored by class RWBTree must inherit abstract base class RWCollectable— the elements are ordered internally according to the value returned by virtual function compareTo() (see class RWCollectable).

This class has certain advantages over class RWBinaryTree. First, the B-tree is automatically balanced. (With class RWBinaryTree, you must call member function balance() explicitly to balance the tree.) Nodes are never allowed to have less than a certain number of items (called the order). The default order is 50, but may be changed by resetting the value of the static constant "order" in the header file <btree.h> and recompiling. Larger values will result in shallower trees, but less efficient use of memory.

Because many keys are held in a single node, class RWBTree also tends to fragment memory less.

Persistence

Polymorphic

Public Constructors

RWBTree();

Construct an empty B-tree.

RWBTree(const RWBTree& btr);

Construct self as a shallow copy of btr.

Public Destructor

virtual RWBTree();

Redefined from RWCollection. Calls clear().

Public Member Operators

void operator=(const RWBTree& btr);

Set self to a shallow copy of btr.

RWBoolean operator<=(const RWBTree& btr) const;

Returns TRUE if self is a subset of btr. That is, for every item in self, there must be an item in btr that compares equal.


Note: If you inherit from RWBTree in the presence of the Standard C++ Library, we recommend that you override this operator and explicitly forward the call. Overload resolution in C++ will choose the Standard Library provided global operators over inherited class members. These global definitions are not appropriate for set-like partial orderings.


RWBoolean operator==(const RWBTree& btr) const;

Returns TRUE if self and btr are equivalent. That is, they must have the same number of items and for every item in self, there must be an item in btr that compares equal.

Public Member Functions

virtual void apply(RWapplyCollectable ap, void*);

Redefined from class RWCollection to apply the user-supplied function pointed to by ap to each member of the collection, in order, from smallest to largest. This supplied function should not do anything to the items that could change the ordering of the collection.

virtual RWspace binaryStoreSize() const;

Inherited from class RWCollection.

virtual void clear();

Redefined from class RWCollection.

virtual void clearAndDestroy();

Inherited from class RWCollection.

virtual int compareTo(const RWCollectable* a) const;

Inherited from class RWCollectable.

virtual RWBoolean contains(const RWCollectable* target) const;

Inherited from class RWCollection.

virtual size_t entries() const;

Redefined from class RWCollection.

virtual RWCollectable* find(const RWCollectable* target) const;

Redefined from class RWCollection. The first item that compares equal to the object pointed to by target is returned or nil if no item is found.

virtual unsigned hash() const;

Inherited from class RWCollectable.

unsigned height() const;

Special member function of this class. Returns the height of the tree, defined as the number of nodes traversed while descending from the root node to an external (leaf) node.

virtual RWCollectable* insert(RWCollectable* c);

Redefined from class RWCollection. Inserts the item c into the collection and returns it. The item c is inserted according to the value returned by compareTo(). If an item is already in the collection which isEqual to c, then the old item is returned and the new item is not inserted. Otherwise returns nil if the insertion was unsuccessful.

virtual RWClassID isA() const;

Redefined from class RWCollectable to return __RWBTREE.

virtual RWBoolean isEmpty() const;

Redefined from class RWCollection.

virtual RWBoolean isEqual(const RWCollectable* a) const;

Inherited from class RWCollectable.

virtual size_t occurrencesOf(const RWCollectable* target) const;

Redefined from class RWCollection. Returns the number of items that compare equal to target. Since duplicates are not allowed, this function can only return 0 or 1.

virtual RWCollectable* remove(const RWCollectable* target);

Redefined from class RWCollection. Removes and returns the first item that compares equal to the object pointed to by target. Returns nil if no item was found.

virtual void removeAndDestroy(const RWCollectable* target);

Inherited from class RWCollection.

virtual void restoreGuts(RWvistream&); virtual void restoreGuts(RWFile&); virtual void saveGuts(RWvostream&) const; virtual void saveGuts(RWFile&) const;

Inherited from class RWCollection.

RWStringID stringID();

(acts virtual) Inherited from class RWCollectable.

RWBTreeDictionary

RWBTreeDictionary ->- RWBTree ->- RWCollection ->- RWCollectable 

Synopsis

#include <rw/btrdict.h>
 
RWBTreeDictionary a;

Description

Dictionary class implemented as a B-tree, for the storage and retrieval of key-value pairs. Both the keys and values must inherit abstract base class RWCollectable— the elements are ordered internally according to the value returned by virtual function compareTo() of the key (see class RWCollectable). Duplicate keys are not allowed.

The B-tree is balanced. That is, nodes are never allowed to have less than a certain number of items (called the order). The default order is 50, but may be changed by resetting the value of the static constant "order" in the header file <btree.h> and recompiling. Larger values will result in shallower trees, but less efficient use of memory.

Persistence

Polymorphic

Public Constructors

RWBTreeDictionary();

Constructs an empty B-tree dictionary.

Public Member Operators

RWBoolean operator<=(const RWBTreeDictionary& btr) const;

Returns TRUE if self is a subset of btr. That is, for every item in self, there must be an item in btr that compares equal. This operator is not explicitly present unless you are compiling with an implementation of the C++ Standard Library. Normally it is inherited from RWBTree.


Note: If you inherit from RWBTreeDictionary in the presence of the C++ Standard Library, we recommend that you override this operator and explicitly forward the call. Overload resolution in C++ will choose the Standard Library provided global operators over inherited class members. These global definitions are not appropriate for set-like partial orderings.


Public Member Functions

void applyToKeyAndValue(RWapplyKeyAndValue ap,void*);

Redefined from class RWCollection. Applies the user-supplied function pointed to by ap to each key-value pair of the collection, in order, from smallest to largest.

RWBinaryTree asBinaryTree(); RWBag asBag() const; RWSet asSet() const; RWOrdered asOrderedCollection() const; RWBinaryTree asSortedCollection() const:

Converts the RWBTreeDictionary to an RWBag, RWSet, RWOrdered, or an RWBinaryTree. Note that since a dictionary contains pairs of keys and values, the result of this call will be a container holding RWCollectableAssociations. Note also that the return value is a copy of the data. This can be very expensive for large collections. Consider using operator+=() to insert each RWCollectableAssociation from this dictionary into a collection of your choice.

virtual RWspace binaryStoreSize() const;

Inherited from class RWCollection.

virtual void clear();

Redefined from class RWCollection. Removes all key-value pairs from the collection.

virtual void clearAndDestroy();

Redefined from class RWCollection. Removes all key-value pairs in the collection, and deletes both the key and the value.

virtual int compareTo(const RWCollectable* a) const;

Inherited from class RWCollectable.

virtual RWBoolean contains(const RWCollectable* target) const;

Inherited from class RWCollection.

virtual size_t entries() const;

Redefined from class RWCollection.

virtual RWCollectable* find(const RWCollectable* target) const;

Redefined from class RWCollection. Returns the key in the collection which compares equal to the object pointed to by target, or nil if no key is found.

RWCollectable* findKeyAndValue(const RWCollectable* target, RWCollectable*& v) const;

Returns the key in the collection which compares equal to the object pointed to by target, or nil if no key was found. The value is put in v. You are responsible for defining v before calling this function.

RWCollectable* findValue(const RWCollectable* target) const;

Returns the value associated with the key which compares equal to the object pointed to by target, or nil if no key was found.

RWCollectable* findValue(const RWCollectable* target, RWCollectable* newValue);

Returns the value associated with the key which compares equal to the object pointed to by target, or nil if no key was found. Replaces the value with newValue (if a key was found).

virtual unsigned hash() const;

Inherited from class RWCollectable.

unsigned height() const;

Inherited from class RWBTree.

RWCollectable* insertKeyAndValue(RWCollectable* key,RWCollectable* value);

Adds a key-value pair to the collection and returns the key if successful, nil if the key is already in the collection.

virtual RWClassID isA() const;

Redefined from class RWCollectable to return __RWBTREEDICTIONARY.

virtual RWBoolean isEmpty() const;

Inherited from class RWBTree.

virtual RWBoolean isEqual(const RWCollectable* a) const;

Inherited from class RWCollectable.

virtual size_t occurrencesOf(const RWCollectable* target) const;

Redefined from class RWCollection. Returns the number of keys that compare equal with target. Because duplicates are not allowed, this function can only return 0 or 1.

virtual RWCollectable* remove(const RWCollectable* target);

Redefined from class RWCollection. Removes the key and value pair for which the key compares equal to the object pointed to by target. Returns the key, or nil if no match was found.

virtual void removeAndDestroy(const RWCollectable* target);

Redefined from class RWCollection. Removes and deletes the key and value pair for which the key compares equal to the object pointed to by target. Note that both the key and the value are deleted. Does nothing if the key is not found.

RWCollectable* removeKeyAndValue(const RWCollectable* target,RWCollectable*& v);

Removes the key and value pair for which the key compares equal to the object pointed to by target. Returns the key, or nil if no match was found. The value is put in v. You are responsible for defining v before calling this function.

virtual void restoreGuts(RWvistream&); virtual void restoreGuts(RWFile&); virtual void saveGuts(RWvostream&) const; virtual void saveGuts(RWFile&) const;

Inherited from class RWCollection.

virtual RWCollection* select(RWtestCollectable testfunc, void* x) const;

Evaluates the function pointed to by tst for the key of each item in the RWBTreeDictionary. It inserts keys and values for which the function returns TRUE into a new RWBTreeDictionary allocated off the heap and returns a pointer to this new collection. Because the new dictionary is allocated off the heap, you are responsible for deleting it when done. This is not a virtual function.

virtual RWCollection* select(RWtestCollectablePair testfunc, void* x) const;

Evaluates the function pointed to by tst for both the key and the value of each item in the RWBTreeDictionary. It inserts keys and values for which the function returns TRUE into a new RWBTreeDictionary allocated off the heap and returns a pointer to this new collection. Because the new dictionary is allocated off the heap, you are responsible for deleting it when done. This is not a virtual function.

RWStringID stringID();

(acts virtual) Inherited from class RWCollectable.

RWBTreeOnDisk

Synopsis

typedef long RWstoredValue;
 
typedef int (*RWdiskTreeCompare)(const char*, const char*,
                                 size_t);
 
#include <rw/disktree.h>
#include <rw/filemgr.h>
RWFileManager fm("filename.dat");
RWBTreeOnDisk bt(fm);

Description

Class RWBTreeOnDisk represents an ordered collection of associations of keys and values, where the ordering is determined by comparing keys using an external function. The user can set this function. Duplicate keys are not allowed. Given a key, the corresponding value can be found.

This class is specifically designed for managing a B-tree in a disk file. Keys, defined to be arrays of chars, and values, defined by the typedef RWstoredValue, are stored and retrieved from a B-tree. The values can represent offsets to locations in a file where objects are stored.

The key length is set by the constructor. By default, this value is 16 characters. By default, keys are null-terminated. However, the tree can be used with embedded nulls, allowing multibyte and binary data to be used as keys. To do so you must:

  • Specify TRUE for parameter ignoreNull in the constructor (see below);

  • Make sure all buffers used for keys are at least as long as the key length (remember, storage and comparison will not stop with a null value);

  • Use a comparison function (such as memcmp()) that ignores nulls.

This class is meant to be used with class RWFileManager which manages the allocation and deallocation of space in a disk file.

When you construct an RWBTreeOnDisk you give the location of the root node in the constructor as argument start. If this value is RWNIL (the default) then the location will be retrieved from the RWFileManager using function start() (see class RWFileManager). You can also use the enumeration createMode to set whether to use an existing tree (creating one if one doesn't exist) or to force the creation of a new tree. The location of the resultant root node can be retrieved using member function baseLocation().

More than one B-tree can exist in a disk file. Each must have its own separate root node. This can be done by constructing more than one RWBTreeOnDisk, each with createMode set to create.

The order of the B-tree can be set in the constructor. Larger values will result in shallower trees, but less efficient use of disk space. The minimum number of entries in a node can also be set. Smaller values may result in less time spent balancing the tree, but less efficient use of disk space.

Persistence

None

Enumerations

enum styleMode {V6Style, V5Style};

This enumeration is used by the constructor to allow backwards compatibility with older V5.X style trees, which supported only 16-byte key lengths. It is used only when creating a new tree. If opening a tree for update, its type is determined automatically at runtime.

 

V6Style

Initialize a new tree using V6.X style trees. This is the default.

 

 

V5Style

Initialize a new tree using V5.X style trees. In this case, the key length is fixed at 16 bytes.


enum createMode {autoCreate, create};

This enumeration is used by the constructor to determine whether to force the creation of a new tree..

 

autoCreate

Look in the location given by the constructor argument start for the root node. If valid, use it. Otherwise, allocate a new tree. This is the default.

 

 

create

Forces the creation of a new tree. The argument start is ignored.


Public Constructor

RWBTreeOnDisk(RWFileManager& f, unsigned nbuf = 10, createMode omode = autoCreate, unsigned keylen = 16, RWBoolean ignoreNull = FALSE, RWoffset start = RWNIL, styleMode smode = V6Style, unsigned halfOrder = 10, unsigned minFill = 10);

Construct a B-tree on disk. The parameters are as follows:

 

f

The file in which the B-tree is to be managed. This is the only required parameter.

 

 

nbuf

The maximum number of nodes that can be cached in memory.

 

 

omode

Determines whether to force the creation of a new tree or whether to attempt to open an existing tree for update (the default).

 

 

keylen

The length of a key in bytes. Ignored when opening an existing tree.

 

 

ignoreNull

Controls whether to allow embedded nulls in keys. If FALSE (the default), then keys end with a terminating null. If TRUE, then all keylen bytes are significant. Ignored when opening an existing tree.

 

start

Where to find the root node. If set to RWNIL (the default), then uses the value returned by the RWFileManager's start() member function. Ignored when creating a new tree.

 

smode

Sets the type of B-tree to create, allowing backwards compatibility (see above). The default specifies new V6.X style B-trees. Ignored when opening an existing tree.

 

 

halfOrder

One half the order of the B-tree (that is, one half the number of entries in a node). Ignored when opening an existing tree.

 

 

minFill

The minimum number of entries allowed in a node (must be less than or equal to halfOrder). Ignored when opening an existing tree.


Public Member Functions

void applyToKeyAndValue((*ap)(const char*,RWstoredValue), void* x);

Visits all items in the collection in order, from smallest to largest, calling the user-provided function pointed to by ap with the key and value as arguments. This function should have the prototype:

void yourApplyFunction(const char* ky,
RWstoredValue val,void* x);

The function yourApplyFunction may not change the key. The value x can be anything and is passed through from the call to applyToKeyAndValue(). This member function may throw an RWFileErr exception.

RWoffset baseLocation() const;

Returns the offset of this tree's starting location within the RWFileManager. This is the value you will pass to a constructor as the start argument when you want to open one of several trees stored in one managed file.

unsigned cacheCount() const;

Returns the maximum number of nodes that may currently be cached.

unsigned cacheCount(unsigned newcount);

Sets the number of nodes that should be cached to newcount. Returns the old number.

void clear();

Removes all items from the collection.This member function may throw an RWFileErr exception.

RWBoolean contains(const char* ky) const;

Returns TRUE if the tree contains a key that is equal to the string pointed to by ky, and FALSE otherwise. This member function may throw an RWFileErr exception.

size_t entries();

Returns the number of items in the RWBTreeOnDisk. This member function may throw an RWFileErr exception.

RWoffset extraLocation(RWoffset newlocation);

Sets the location where this RWBTreeOnDisk keeps your own application-specific information to newlocation. Returns the previous value.

RWBoolean findKey(const char* ky,RWCString& foundKy)const ;

Returns TRUE if ky is found, otherwise FALSE. If successful, the found key is returned as a reference in foundKy. This member function may throw an RWFileErr exception.

RWBoolean findKeyAndValue( const char* ky, RWCString& foundKy, RWStoredValue& foundVal)const ;

Returns TRUE if ky is found, otherwise FALSE. If successful, the found key is returned as a reference in foundKy, and the value is returned as a reference in foundVal. This member function may throw an RWFileErr exception.

RWstoredValue findValue(const char* ky)const;

Returns the value for the key that compares equal to the string pointed to by ky. Returns RWNIL if no key is found. This member function may throw an RWFileErr exception.

int height();

Returns the height of the RWBTreeOnDisk. A possible exception is RWFileErr.

int insertKeyAndValue(const char* ky,RWstoredValue v);

Adds a key-value pair to the B-tree. Returns TRUE for successful insertion, FALSE otherwise. A possible exception is RWFileErr.

unsigned keyLength() const;

Return the length of the keys for this RWBtreeOnDisk. This number is set when the tree is first constructed and cannot be changed.

unsigned minOrder()const;

Return the minimum number of items that may be found in any non-root node in this RWBtreeOnDisk. This number is set when the tree is first constructed and cannot be changed.

unsigned nodeSize() const;

Returns the number of bytes used by each node of this RWBTreeOnDisk. This number is calculated from the length of the keys and the order of the tree, and cannot be changed. We make it available to you for your calculations about how many nodes to cache.

unsigned order()const;

Return half the maximum number of items that may be stored in any node in this RWBtreeOnDisk. This number is set when the tree is first constructed and cannot be changed. This method should have been renamed "halfOrder" but is still called "order" for backward compatibility.

RWBoolean isEmpty() const;

Returns TRUE if the RWBTreeOnDisk is empty, otherwise FALSE.

void remove(const char* ky);

Removes the key and value pair that has a key which matches ky. This member function may throw an RWFileErr exception.

RWBoolean replaceValue(const RWCString& key, const RWstoredValue newval, RWstoredValue& oldVal);

Attempts to replace the RWstoredValue now associated with key by the value newval. If successful, the previous value is returned by reference in oldVal; and the methed returns TRUE. Otherwise, returns FALSE.

RWdiskTreeCompare setComparison(RWdiskTreeCompare fun);

Changes the comparison function to fun and returns the old function. This function must have prototype:

int yourFun(const char* key1, const char* key2, size_t N);

It should return a number less than zero, equal to zero, or greater than zero depending on whether the first argument is less than, equal to or greater than the second argument, respectively. The third argument is the key length. Possible choices (among others) are strncmp() (the default), or strnicmp() (for case-independent comparisons).

RWBufferedPageHeap

RWBufferedPageHeap ->- RWVirtualPageHeap 

Synopsis

#include <rw/bufpage.h>
 
(Abstract base class ) 

Description

This is an abstract base class that represents an abstract page heap buffered through a set of memory buffers. It inherits from the abstract base class RWVirtualPageHeap, which represents an abstract page heap.

RWBufferedPageHeap will supply and maintain a set of memory buffers. Specializing classes should supply the actual physical mechanism to swap pages in and out of these buffers by supplying definitions for the pure virtual functions swapIn(RWHandle, void*) and swapOut(RWHandle, void*).

The specializing class should also supply appropriate definitions for the public functions allocate() and deallocate(RWHandle).

For a sample implementation of a specializing class, see class RWDiskPageHeap.

Persistence

None

Public Constructor

RWBufferedPageHeap(unsigned pgsize, unsigned nbufs=10);

Constructs a buffered page heap with page size pgsize. The number of buffers (each of size pgsize) that will be allocated on the heap will be nbufs. If there is insufficient memory to satisfy the request, then the state of the resultant object as returned by member function isValid() will be FALSE, otherwise, TRUE.

Protected Member Functions

virtual RWBoolean swapIn(RWHandle h, void* buf) = 0; virtual RWBoolean swapOut(RWHandle, h void* buf) = 0;

It is the responsibility of the specializing class to supply definitions for these two pure virtual functions. Function swapOut() should copy the page with handle h from the buffer pointed to by buf to the swapping medium. Function swapIn() should copy the page with handle h into the buffer pointed to by buf.

Public Member Functions

virtual RWHandle allocate() = 0;

It is the responsibility of the specializing class to supply a definition for this pure virtual function. The specializing class should allocate a page and return a unique handle for it. It should return zero if it cannot satisfy the request. The size of the page is set by the constructor.

virtual ~RWBufferedPageHeap();

Deallocates all internal buffers.

RWBoolean isValid();

Returns TRUE if self is in a valid state. A possible reason why the object might not be valid is insufficient memory to allocate the internal buffers.

virtual void deallocate(RWHandle h);

Redefined from class RWVirtualPageHeap. It is never an error to call this function with argument zero. Even though this is not a pure virtual function, it is the responsibility of the specializing class to supply an appropriate definition for this function. All this definition does is release any buffers associated with the handle h. Just as the actual page allocation is done by the specializing class through virtual function allocate(), so must the actual deallocation be done by overriding deallocate().

virtual void dirty(RWHandle h);

Redefined from class RWVirtualPageHeap.

virtual void* lock(RWHandle h);

Redefined from class RWVirtualPageHeap.

virtual void unlock(RWHandle h);

Redefined from class RWVirtualPageHeap.

RWCacheManager

Synopsis

#include <rw/cacheman.h>
 
RWFile f("file.dat");       // Construct a file
RWCacheManager(&f, 100);    // Cache 100 byte blocks to file.dat

Description

Class RWCacheManager caches fixed length blocks to and from an associated RWFile. The block size can be of any length and is set at construction time. The number of cached blocks can also be set at construction time.

Writes to the file may be deferred. Use member function flush() to have any pending writes performed.

Persistence

None

Example

#include <rw/cacheman.h>
#include <rw/rwfile.h>
 
struct Record {
  int i;
  float f;
  char str[15];
};
main(){
   RWoffset loc;
   RWFile file("file.dat");     // Construct a file
 
   // Construct a cache, using 20 slots for struct Record:
      RWCacheManager cache(&file, sizeof(Record), 20);
 
   Record r;
   // ...
   cache.write(loc, &r);
   // ...
   cache.read(loc, &r);
}

Public Constructor

RWCacheManager(RWFile* file, unsigned blocksz, unsigned mxblks = 10);

Construct a cache for the RWFile pointed to by file. The length of the fixed-size blocks is given by blocksz. The number of cached blocks is given by mxblks. If the total number of bytes cached would exceed the maximum value of an unsigned int, then RWCacheManager will quietly decide to cache a smaller number of blocks.

Public Destructor

~RWCacheManager();

Performs any pending I/O operations (i.e., calls flush()) and deallocates any allocated memory.

Public Member Functions

RWBoolean flush();

Perform any pending I/O operations. Returns TRUE if the flush was successful, FALSE otherwise.

void invalidate();

Invalidate the cache.

RWBoolean read(RWoffset locn, void* dat);

Return the data located at offset locn of the associated RWFile. The data is put in the buffer pointed to by dat. This buffer must be at least as long as the block size specified when the cache was constructed. Returns TRUE if the operation was successful, otherwise FALSE.

RWBoolean write(RWoffset locn, void* dat);

Write the block of data pointed to by dat to the offset locn of the associated RWFile. The number of bytes written is given by the block size specified when the cache was constructed. The actual write to disk may be deferred. Use member function flush() to perform any pending output. Returns TRUE if the operation was successful, otherwise FALSE.

RWCLIPstreambuf

RWCLIPstreambuf ->- streambuf 

Synopsis

#include <rw/winstrea.h>
 
#include <iostream.h>
iostream str( new RWCLIPstreambuf() );

Description

Class RWCLIPstreambuf is a specialized streambuf that gets and puts sequences of characters to Microsoft Windows global memory. It can be used to exchange data through Windows clipboard facility.

The class has two modes of operation: dynamic and static. In dynamic mode, memory is allocated and reallocated as needed. If too many characters are inserted into the internal buffer for its present size, then it will be resized and old characters copied over into any new memory as necessary. This is transparent to the user. It is expected that this mode would be used primarily for "insertions," i.e., clipboard "cuts" and "copies." In static mode, the buffer streambuf is constructed from a specific piece of memory. No reallocations will be done. It is expected that this mode would be used primarily for "extractions," i.e., clipboard "pastes."

In dynamic mode, the RWCLIPstreambuf "owns" any allocated memory until the member function str() is called, which "freezes" the buffer and returns an unlocked Windows handle to it. The effect of any further insertions is undefined. Until str() has been called, it is the responsibility of the RWCLIPstreambuf destructor to free any allocated memory. After the call to str(), it becomes the user's responsibility.

In static mode, the user has the responsibility for freeing the memory handle. However, because the constructor locks and dereferences the handle, you should not free the memory until either the destructor or str() has been called, either of which will unlock the handle.

Persistence

None

Example

//Instructions:  compile as a Windows program.
//Run this program, then using your favorite text editor or word
//processor, select paste and see the result!
 
#include <rw/winstrea.h>
 
#include <stdlib.h>
#include <iostream.h>
#include <windows.h>
 
 
void postToClipboard(HWND owner);
 
main()
{
   postToClipboard(NULL);
 
   return 0;
}
 
// PASS YOUR WINDOW HANDLE TO THIS FUNCTION THEN PASS YOUR VALUES
// TO THE CLIPBOARD USING ostr.
 
void postToClipboard(HWND owner)
{
   //Build the clipstream buffer on the heap
   RWCLIPstreambuf* buf = new
   RWCLIPstreambuf();
 
   ostream ostr(buf);
 
   double d = 12.34;
 
   ostr << "Some text to be exchanged through the clipboard.\n";
   ostr << "Might as well add a double: " << d << endl;
   ostr.put('\0');        // Include the terminating null
 
   // Lock the streambuf, get its handle:
   HANDLE hMem = buf->str();
 
   OpenClipboard(owner);
 
   EmptyClipboard();
   SetClipboardData(CF_TEXT, hMem);
   CloseClipboard();
 
   // Don't delete the buffer!.  Windows is now responsible for it.
}

The owner of the clipboard is passed in as parameter "owner". A conventional ostream is created, except that it uses an RWCLIPstreambuf as its associated streambuf. It can be used much like any other ostream, such as cout, except that characters will be inserted into Windows global memory.

Some text and a double is inserted into the ostream. Finally, member function str() is called which returns a Windows HANDLE. The clipboard is then opened, emptied, and the new data put into it with format CF_TEXT which, in this case, is appropriate because a simple ostream was used to format the output. If a specializing virtual streams class such as RWbostream or RWpostream had been used instead, the format is not so simple. In this case, the user might want to register his or her own format, using the Windows function RegisterClipboardFormat().

Public Constructors

RWCLIPstreambuf();

Constructs an empty RWCLIPstreambuf in dynamic mode. The results can be used anywhere any other streambuf can be used. Memory to accomodate new characters will be allocated as needed.

RWCLIPstreambuf(HANDLE hMem);

Constructs an RWCLIPstreambuf in static mode, using the memory block with global handle hMem. The effect of gets and puts beyond the size of this memory block is unspecified.

Public Destructor

~RWCLIPstreambuf();

If member function str() has not been called, the destructor unlocks the handle and, if in dynamic mode, also frees it.

Public Member Functions

Because RWCLIPstreambuf inherits from streambuf, any of the latter's member functions can be used. Furthermore, RWCLIPstreambuf has been designed to be analogous to strstreambuf. However, note that the return type of str() is a HANDLE, rather than a char*.

HANDLE str();

Returns an (unlocked) HANDLE to the global memory being used. The RWCLIPstreambuf should now be regarded as "frozen": the effect of inserting any more characters is undefined. If the RWCLIPstreambuf was constructed in dynamic mode, and nothing has been inserted, then the returned HANDLE may be NULL. If it was constructed in static mode, then the returned handle will be the handle used to construct the RWCLIPstreambuf.

RWCollectable

Synopsis

typedef RWCollectable Object;  // Smalltalk typedef
 
#include <rw/collect.h>

Description

Class RWCollectable is an abstract base class for collectable objects. This class contains virtual functions for identifying, hashing, comparing, storing and retrieving collectable objects. While these virtual functions have simple default definitions, objects that inherit this base class will typically redefine one or more of them.

Persistence

Polymorphic

Virtual Functions

virtual ~RWCollectable();

All functions that inherit class RWCollectable have virtual destructors. This allows them to be deleted by such member functions as removeAndDestroy() without knowing their type.

virtual RWspace binaryStoreSize() const;

Returns the number of bytes used by the virtual function saveGuts(RWFile&) to store an object. Typically, this involves adding up the space required to store all primitives, plus the results of calling recursiveStoreSize() for all objects inheriting from RWCollectable. See the Tool.h++ User's Guide Section entitled "Virtual Function binaryStoreSize" for details.

virtual int compareTo(const RWCollectable*) const;

The function compareTo() is necessary to sort the items in a collection. If p1 and p2 are pointers to RWCollectable objects, the statement

p1->compareTo(p2);

should return:

0 if *p1 "is equal to" *p2;

>0 if *p1 is "larger" than *p2;

<0 if *p1 is "smaller" than *p2.

Note that the meaning of "is equal to," "larger" and "smaller" is left to the user. The default definition provided by the base class is based on the addresses, i.e. the meaning of "is equal to," "larger" and "smaller" is left to the user. The default definition provided by the base class is based on the addresses, i.e.,

return this == p2 ? 0 : (this > p2 ? 1 : -1);

and is probably not very useful.

virtual unsigned hash() const;

Returns a hash value. This function is necessary for collection classes that use hash table look-up. The default definition provided by the base class hashes the object's address:

return (unsigned)this;

It is important that the hash value be the same for all objects which return TRUE to isEqual().

virtual RWClassID isA()const;

Returns a class identification number (typedef'd to be an unsignedshort). The default definition returns __RWCOLLECTABLE. Identification numbers greater than or equal to 0x8000 (hex) are reserved for Rogue Wave objects. User defined classes should define isA() to return a number between 0 and 0x7FFF.

virtual RWBoolean isEqual(const RWCollectable* t) const;

Returns TRUE if collectable object "matches" object at address t. The default definition is:

return this == t;

i.e., both objects have the same address (a test for identity). The definition may be redefined in any consistent way.

virtual RWCollectable* newSpecies() const;

Allocates a new object off the heap of the same type as self and returns a pointer to it. You are responsible for deleting the object when done with it.

virtual void restoreGuts(RWFile&);

Read an object's state from a binary file, using class RWFile, replacing the previous state.

virtual void restoreGuts(RWvistream&);

Read an object's state from an input stream, replacing the previous state.

virtual void saveGuts(RWFile&) const;

Write an object's state to a binary file, using class RWFile.

virtual void saveGuts(RWvostream&) const;

Write an object's state to an output stream.

RWStringID stringID();

Returns the identification string for the class. Acts virtual, although it is not.[2]

RWspace recursiveStoreSize() const;

Returns the number of bytes required to store the object using the global operator

RWFile& operator<<(RWFile&, const RWCollectable&);

Recursively calls binaryStoreSize(), taking duplicate objects into account.

Static Public Member Functions

static RWClassID classID(const RWStringID& name);

Returns the result of looking up the RWClassID associated with name in the global RWFactory.

static RWClassID classIsA();

Returns the RWClassID of this class.

static RWBoolean isAtom(RWClassID id);

Returns TRUE if id is the RWClassID that is associated with an RWCollectable class that has a programmer-chosen RWStringID.

static RWspace nilStoreSize();

Returns the number of bytes required to store a rwnil pointer in an RWFile.

Related Global Operators

RWvostream& operator<<(RWvostream&, const RWCollectable& obj); RWFile& operator<<(RWFile&, const RWCollectable& obj);

Saves the object obj to a virtual stream or RWFile, respectively. Recursively calls the virtual function saveGuts(), taking duplicate objects into account. See the Tools.h++ User's Guide section entitled "Persistence" for more information.

RWvistream& operator>>(RWvistream&, RWCollectable& obj); RWFile& operator>>(RWFile&, RWCollectable& obj);

Restores an object inheriting from RWCollectable into obj from a virtual stream or RWFile, respectively, replacing the previous contents of obj. Recursively calls the virtual function restoreGuts(), taking duplicate objects into account. See the Tools.h++ User's Guide section entitled "Persistence" for more information. Various exceptions that could be thrown are RWInternalErr (if the RWFactory does not know how to make the object), and RWExternalErr (corrupted stream or file).

RWvistream& operator>>(RWvistream&, RWCollectable*& obj); RWFile& operator>>(RWFile&, RWCollectable*& obj);

Looks at the next object on the input stream or RWFile, respectively, and either creates a new object of the proper type off the heap and returns a pointer to it, or else returns a pointer to a previously read instance. Recursively calls the virtual function restoreGuts(), taking duplicate objects into account. If an object is created off the heap, then you are responsible for deleting it. See the Tools.h++ User's Guide section entitled "Persistence" for more information. Various exceptions that could be thrown are RWInternalErr (if the RWFactory does not know how to make the object), and RWExternalErr (corrupted stream or file). In case an exception is thrown during this call, the pointer to the partly restored object will probably be lost, and memory will leak. For this reason, you may prefer to use the static methods tryRecursiveRestore() documented above.

RWCollectableAssociation

RWCollectableAssociation ->- RWCollectable 

Synopsis

#include <rw/collass.h> 

Description

RWCollectableAssociation inherits class RWCollectable. Used internally to associate a key with a value in the Tools.h++ "dictionary" collection classes. Comparison and equality testing are forwarded to the key part of the association.

Persistence

Polymorphic

Related Classes

The "dictionary containers" RWBTreeDictionary, RWHashDictionary, and RWIdentityDictionary make use of RWCollectableAssociation. When any of their contents is dealt with as an RWCollectable, as when operator+=() or asBag() etc. is used, the RWCollectableAssociation will be exposed.

Public Constructors

RWCollectableAssociation(); RWCollectableAssociation(RWCollectable* k, RWCollectable* v);

Construct an RWCollectableAssociation with the given key and value.

Public Destructor

virtual ~RWCollectableAssociation(); virtual RWspace

binaryStoreSize() const;

Redefined from class RWCollectable.

Public Member Functions

virtual int compareTo(const RWCollectable* c) const;

Redefined from class RWCollectable. Returns the results of calling key()->compareTo(c).

virtual unsigned hash() const;

Redefined from class RWCollectable. Returns the results of calling key()->hash().

virtual RWClassID isA() const;

Redefined from class RWCollectable to return __RWCOLLECTABLEASSOCIATION.

virtual RWBoolean isEqual(const RWCollectable* c) const;

Redefined from class RWCollectable. Returns the results of calling key()->isEqual(c).

RWCollectable* key() const;

Returns the key part of the association.

RWCollectable* value() const;

Returns the value part of the association.

RWCollectable* value(RWCollectable* ct);

Sets the value to ct and returns the old value.

virtual void restoreGuts(RWvistream&); virtual void restoreGuts(RWFile&); virtual void saveGuts(RWvostream&) const; virtual void saveGuts(RWFile&) const;

Redefined from class RWCollectable.

RWCollectableDate

                 ->- RWCollectable 
RWCollectableDate 
                 ->- RWDate 

Synopsis

typedef RWCollectableDate Date; // Smalltalk typedef
 
#include <rw/colldate.h>
RWCollectableDate  d;

Description

Collectable Dates. Inherits classes RWDate and RWCollectable. This class is useful when dates are used as keys in the "dictionary" collection classes, or if dates are stored and retrieved as RWCollectables. The virtual functions of the base class RWCollectable have been redefined.

Persistence

Polymorphic

Public Constructors

RWCollectableDate(); RWCollectableDate(unsigned long julianDate); RWCollectableDate(unsigned day, unsigned year); RWCollectableDate(unsigned day, unsigned month, unsigned year); RWCollectableDate(unsigned day, const char* mon, unsigned year,const RWLocale& locale = RWLocale::global()); RWCollectableDate(istream& s, const RWLocale& locale = RWLocale::global()); RWCollectableDate(const RWCString& str,const RWLocale& locale = RWLocale::global()); RWCollectableDate(const RWTime& t, const RWZone& zone = RWZone::local()); RWCollectableDate(const struct tm* tmb); RWCollectableDate(const RWDate& d);

Calls the corresponding constructor of the base class RWDate.

Public Member Functions

virtual RWspace binaryStoreSize() const;

Redefined from class RWCollectable.

virtual int compareTo(const RWCollectable* c) const;

Redefined from class RWCollectable. Returns the results of calling RWDate::compareTo.

virtual unsigned hash() const;

Redefined from class RWCollectable. Returns the results of calling RWDate::hash().

virtual RWClassID isA() const;

Redefined from class RWCollectable to return __RWCOLLECTABLEDATE.

virtual RWBoolean isEqual(const RWCollectable* t) const;

Redefined from class RWCollectable. Returns the results of calling operator==() for the base class RWDate by using appropriate casts.

virtual void restoreGuts(RWvistream&); virtual void restoreGuts(RWFile&); virtual void saveGuts(RWvostream&) const; virtual void saveGuts(RWFile&) const;

Redefined from class RWCollectable.

RWStringID stringID();

(acts virtual) Inherited from class RWCollectable.

RWCollectableInt

                 ->- RWCollectable 
RWCollectableInt 
                 ->- RWInteger 

Synopsis

typedef RWCollectableInt Integer;  // Smalltalk typedef
 
#include <rw/collint.h>
RWCollectableInt  i;
Description 

Collectable integers. Inherits classes RWInteger and RWCollectable. This class is useful when integers are used as keys in the "dictionary" collection classes, or if integers are stored and retrieved as RWCollectables. The virtual functions of the base class RWCollectable have been redefined.

Persistence

Polymorphic

Public Constructors

RWCollectableInt();

Calls the appropriate base class constructor. See RWInteger::RWInteger().

RWCollectableInt(int i);

Calls the appropriate base class constructor. See RWInteger::RWInteger(int).

Public Member Functions

virtual RWspace binaryStoreSize() const;

Redefined from class RWCollectable.

virtual int compareTo(const RWCollectable* c) const;

Redefined from class RWCollectable. Returns the difference between self and the RWCollectableInt pointed to by c.

virtual unsigned hash() const;

Redefined from class RWCollectable. Returns the RWCollectableInt's value as an unsigned, to be used as a hash value.

virtual RWClassID isA() const;

Redefined from class RWCollectable to return __RWCOLLECTABLEINT.

virtual RWBoolean isEqual(const RWCollectable* c) const;

Redefined from class RWCollectable. Returns TRUE if self has the same value as the RWCollectableInt at address c.

virtual void restoreGuts(RWvistream&); virtual void restoreGuts(RWFile&); virtual void saveGuts(RWvostream&) const; virtual void saveGuts(RWFile&) const;

Redefined from class RWCollectable.

RWStringID stringID();

(acts virtual) Inherited from class RWCollectable.

RWCollectableString

                   ->- RWCollectable 
RWCollectableString 
                   ->- RWCString 

Synopsis

typedef RWCollectableString String; // Smalltalk typedef
 
#include <rw/collstr.h>
RWCollectableString  c;

Description

Collectable strings. This class is useful when strings are stored and retrieved as RWCollectables, or when they are used as keys in the "dictionary" collection classes. Class RWCollectableString inherits from both class RWCString and class RWCollectable. The virtual functions of the base class RWCollectable have been redefined.

Persistence

Polymorphic

Public Constructors

RWCollectableString();

Construct an RWCollectableString with zero characters.

RWCollectableString(const RWCString& s);

Construct an RWCollectableString from the RWCStrings.

RWCollectableString(const char* c);

Conversion from character string.

RWCollectableString(const RWCSubString&);

Conversion from sub-string.

RWCollectableString(char c, size_t N);

Construct an RWCollectableString with N characters (default blanks).

Public Member Functions

virtual RWspace binaryStoreSize() const;

Redefined from class RWCollectable.

virtual int compareTo(const RWCollectable* c) const;

Redefined from class RWCollectable. returns the result of RWCString::compareTo(*(const String*)c, RWCString::exact). This compares strings lexicographically, with case considered. It would be possible to define , for instance, CaseFoldedString which did comparisons ignoring case. We have deliberately left this as an exercise for two reasons: Because it is both easy to do and not universally needed; and because the presence of both RWCollectableStrings and such a CaseFoldedString in any kind of sorted collection has the potential for very confusing behavior, since the result of a comparison would depend on the order in which the comparison was done.

virtual unsigned hash() const;

Redefined from class RWCollectable. Calls RWCString::hash() and returns the results.

virtual RWClassID isA() const;

Redefined from class RWCollectable to return __RWCOLLECTABLESTRING.

virtual RWBoolean isEqual(const RWCollectable* c) const;

Redefined from class RWCollectable. Calls RWCString::operator==() (i.e., the equivalence operator) with c as the argument and returns the results.

virtual void restoreGuts(RWvistream&); virtual void restoreGuts(RWFile&); virtual void saveGuts(RWvostream&) const; virtual void saveGuts(RWFile&) const;

Redefined from class RWCollectable.

RWStringID stringID();

(acts virtual) Inherited from class RWCollectable.

RWCollectableTime

                  ->- RWCollectable 
RWCollectableTime 
                  ->- RWTime 

Synopsis

typedef RWCollectableTime Time; // Smalltalk typedef
 
#include <rw/colltime.h>
RWCollectableTime  t;

Description

Inherits classes RWTime and RWCollectable. This class is useful when times are used as keys in the "dictionary" collection classes, or if times are stored and retrieved as RWCollectables. The virtual functions of the base class RWCollectable have been redefined.

Persistence

Polymorphic

Public Constructors

RWCollectableTime(); RWCollectableTime(unsigned long s); RWCollectableTime(unsigned hour, unsigned minute, unsigned sec = 0,const RWZone& zone = RWZone::local()); RWCollectableTime(const RWDate& day, unsigned hour=0, unsigned minute=0, unsigned sec = 0, const RWZone& zone = RWZone::local()); RWCollectableTime(const RWDate& day, const RWCString& str, const RWZone& zone = RWZone::local(), const RWLocale& locale = RWLocale::global()); RWCollectableTime(const struct tm* tmb, const RWZone& zone = RWZone::local());

Calls the corresponding constructor of RWTime.

Public Member Functions

virtual RWspace binaryStoreSize() const;

Redefined from class RWCollectable.

virtual int compareTo(const RWCollectable* c) const;

Redefined from class RWCollectable. Returns the results of calling RWTime::compareTo.

virtual unsigned hash() const;

Redefined from class RWCollectable. Returns the results of calling RWTime::hash().

virtual RWClassID isA() const;

Redefined from class RWCollectable to return __RWCOLLECTABLETIME.

virtual RWBoolean isEqual(const RWCollectable* c) const;

Redefined from class RWCollectable. Returns the results of calling operator==() for the base class RWTime by using appropriate casts.

virtual void restoreGuts(RWvistream&);

virtual void restoreGuts(RWFile&);

virtual void saveGuts(RWvostream&) const;

virtual void saveGuts(RWFile&) const;

Redefined from class RWCollectable.

RWStringID stringID();

(acts virtual) Inherited from class RWCollectable.

RWCollection

RWCollection ->- RWCollectable 

Synopsis

#include <rw/colclass.h>
 
typedef RWCollection Collection;   // Smalltalk typedef

Description

Class RWCollection is an abstract base class for the Smalltalk-like collection classes. The class contains virtual functions for inserting and retrieving pointers to RWCollectable objects into the collection classes. Virtual functions are also provided for storing and reading the collections to files and streams. Collections that inherit this base class will typically redefine one or more of these functions.

In the documentation below, pure virtual functions are indicated by "= 0" in their declaration. These functions must be defined in derived classes. For these functions the description is intended to be generic — all inheriting collection classes generally follow the described pattern. Exceptions are noted in the documentation for the particular class.

For many other functions, a suitable definition is provided by RWCollection and a deriving class may not need to redefine the function. Examples are contains() or restoreGuts().

Persistence

Polymorphic

Public Member Operators

void operator+=(const RWCollection&); void operator-=(const RWCollection&);

Adds or removes, respectively, each item in the argument to or from self. Using operator+=(somePreSortedCollection) on an RWBinaryTree can cause that tree to become unbalanced; possibly to the point of stack overflow.

Public Member Functions

virtual ~RWCollection();

Null definition (does nothing).

virtual void apply(RWapplyCollectable ap, void*) = 0;

This function applies the user-supplied function pointed to by ap to each member of the collection. This function should have prototype

void yourApplyFunction(RWCollectable* ctp, void*);

The function yourApplyFunction() can perform any operation on the item at address ctp that does not change the hash value or sorting order of the item. Client data may be passed to this function through the second argument.

RWBag asBag() const; RWSet asSet() const; RWOrdered asOrderedCollection() const; RWBinaryTree asSortedCollection() const;

Allows any collection to be converted to an RWBag, RWSet, RWOrdered, or an RWBinaryTree. Note that the return value is a copy of the data. This can be very expensive for large collections. You should consider using operator+=() to insert each item from this collection into a collection of your choice. Also note that converting a collection containing data which is already sorted to a RWBinaryTree via the asSortedCollection() or asBinaryTree() methods will build a very unbalanced tree.

virtual RWspace binaryStoreSize() const;

Redefined from class RWCollectable.

virtual void clear() = 0;

Removes all objects from the collection. Does not delete the objects themselves.

virtual void clearAndDestroy();

Removes all objects from the collection and deletes them. Takes into account duplicate objects within a collection and only deletes them once. However, it does not take into account objects shared between different collections. Either do not use this function if you will be sharing objects between separate collections, or put all collections that could be sharing objects into one single "super-collection" and call clearAndDestroy() on that.

virtual int compareTo(const RWCollectable* a) const;

Inherited from class RWCollectable.

virtual RWBoolean contains(const RWCollectable* target) const;

Returns TRUE if the collection contains an item where the virtual function find() returns non-nil.

virtual size_t entries() const = 0;

Returns the total number of items in the collection.

virtual RWCollectable* find(const RWCollectable* target) const = 0;

Returns a pointer to the first item in the collection which "matches" the object pointed to by target or nil if no item was found. For most collections, an item "matches" the target if either isEqual() or compareTo() find equivalence, whichever is appropriate for the actual collection type. However, the "identity collections" (i.e., RWIdentitySet and RWIdentityDictionary) look for an item with the same address (i.e., "is identical to").

virtual unsigned hash() const;

Inherited from class RWCollectable.

virtual RWCollectable* insert(RWCollectable* e) = 0;

Adds an item to the collection and returns a pointer to it. If the item is already in the collection, some collections derived from RWCollection return the old instance, others return nil.

virtual RWClassID isA() const;

Redefined from class RWCollectable to return __RWCOLLECTION.

virtual RWBoolean isEmpty() const = 0;

Returns TRUE if the collection is empty, otherwise returns FALSE.

virtual RWBoolean isEqual(const RWCollectable* a) const;

Inherited from class RWCollectable.

virtual size_t occurrencesOf(const RWCollectable* t) const = 0;

Returns the number of items in the collection which are "matches" t. See function find() for a definition of matches.

virtual void restoreGuts(RWFile&);

Redefined to repeatedly call the global operator

RWFile& operator>>(RWFile&, RWCollectable*&);

followed by insert(RWCollectable*) for each item in the collection.

virtual void restoreGuts(RWvistream&);

Redefined to repeatedly call the global operator

RWvistream& operator>>(RWvistream&, RWCollectable*&);

followed by insert(RWCollectable*) for each item in the collection.

RWCollectable* remove(const RWCollectable* target) = 0;

Removes and returns a pointer to the first item in the collection which "matches" the object pointed to by target. Returns nil if no object was found. Does not delete the object.

virtual void removeAndDestroy(const RWCollectable* target);

Removes and deletes the first item in the collection which "matches" the object pointed to by target.

RWCollection* select(RWtestCollectable tst, void* x) const;

Evaluates the function pointed to by tst for each item in the collection. It inserts those items for which the function returns TRUE into a new collection allocated off the heap of the same type as self and returns a pointer to this new collection. Because the new collection is allocated off the heap, you are responsible for deleting it when done. This is not a virtual function.

virtual void saveGuts(RWFile&);

Redefined to call the global operator

RWFile& operator<<(RWFile&, const RWCollectable&);

for each object in the collection.

virtual void saveGuts(RWvostream&);

Redefined to call the global operator

RWvostream& operator<<(RWvostream&, const RWCollectable&);

for each object in the collection.

RWCRegexp

Synopsis

#include <rw/regexp.h>
 
RWCRegexp re(".*\\.doc");// Matches filename with suffix ".doc"

Description

Class RWCRegexp represents a regular expression. The constructor "compiles" the expression into a form that can be used more efficiently. The results can then be used for string searches using class RWCString.

The regular expression (RE) is constucted as follows:

The following rules determine one-character REs that match a single character:

  1. Any character that is not a special character (to be defined) matches itself.

  2. A backslash (\) followed by any special character matches the literal character itself. i.e., this "escapes" the special character.

  3. The "special characters" are:

+ * ? . [ ] ^ $

  1. The period (.) matches any character except the newline. E.g., ".umpty" matches either "Humpty" or "Dumpty."

  2. A set of characters enclosed in brackets ([]) is a one-character RE that matches any of the characters in that set. E.g., "[akm]" matches either an "a", "k", or "m". A range of characters can be indicated with a dash. E.g., "[a-z]" matches any lower-case letter. However, if the first character of the set is the caret (^), then the RE matches any character except those in the set. It does not match the empty string. Example: [^akm] matches any character except "a", "k", or "m". The caret loses its special meaning if it is not the first character of the set.

The following rules can be used to build a multicharacter RE.

  1. A one-character RE followed by an asterisk (*) matches zero or more occurrences of the RE. Hence, [a-z]* matches zero or more lower-case characters.

  2. A one-character RE followed by a plus (+) matches one or more occurrences of the RE. Hence, [a-z]+ matches one or more lower-case characters.

  3. A question mark (?) is an optional element. The preceeding RE can occur zero or once in the string — no more. E.g. xy?z matches either xyz or xz.

  4. The concatenation of REs is a RE that matches the corresponding concatenation of strings. E.g., [A-Z][a-z]* matches any capitalized word.

Finally, the entire regular expression can be anchored to match only the beginning or end of a line:

  1. If the caret (^) is at the beginning of the RE, then the matched string must be at the beginning of a line.

  2. If the dollar sign ($) is at the end of the RE, then the matched string must be at the end of the line.

The following escape codes can be used to match control characters:

\b backspace

\e ESC (escape)

\f formfeed

\n newline

\r carriage return

\t tab

\xddd the literal hex number 0xdd

\ddd the literal octal number ddd

\^C Control code. E.g. \^D is "control-D"

Persistence

None

Example

#include <rw/regexp.h>
#include <rw/cstring.h>
#include <rw/rstream.h>
 
main(){
   RWCString aString("Hark! Hark! the lark");
 
   // A regular expression matching any lower-case word
   // starting with "l":
   RWCRegexp reg("l[a-z]*");
 
   cout << aString(reg) << endl;  // Prints "lark"
}

RWCRegexp(const char* pat);

Construct a regular expression from the pattern given by pat. The status of the results can be found by using member function status().

RWCRegexp(const RWCRegexp& r);

Copy constructor. Uses value semantics — self will be a copy of r.

Public Destructor

~RWCRegexp();

Destructor. Releases any allocated memory.

Assignment Operators

RWCRegexp& operator=(const RWCRegexp&);

Uses value semantics — sets self to a copy of r.

RWCRegexp& operator=(const char* pat);

Recompiles self to the pattern given by pat. The status of the results can be found by using member function status().

Public Member Functions

size_t index(const RWCString& str,size_t* len, size_t start=0) const;

Returns the index of the first instance in the string str that matches the regular expression compiled in self, or RW_NPOS if there is no such match. The search starts at index start. The length of the matching pattern is returned in the variable pointed to by len. If an invalid regular expression is used for the search, an exception of type RWInternalErr will be thrown. Note that this member function is relatively clumsy to use — class RWCString offers a better interface to regular expression searches.

statVal status();

Returns the status of the regular expression and resets status to OK:

Table 2-1. statVal regular expression status

statVal

Meaning

RWCRegexp::OK

No errors

RWCRegexp::ILLEGAL

Pattern was illegal

RWCRegexp::TOOLONG

Pattern exceeded maximum length


RWCRExpr

Synopsis

#include <rw/re.h>
 
RWCRExpr re(".*\\.doc");  // Matches filename with suffix ".doc"

Description

Class RWCRExpr represents an extended regular expression such as those found in lex and awk. The constructor "compiles" the expression into a form that can be used more efficiently. The results can then be used for string searches using class RWCString. Regular expressions can be of arbitrary size, limited by memory. The extended regular expression features found here are a subset of those found in the POSIX.2 standard (ANSI/IEEE Std 1003.2, ISO/IEC 9945-2).


Note: RWCRExpr is available only if your compiler supports exception handling and the C++ Standard Library.

The regular expression (RE) is constructed as follows:

The following rules determine one-character REs that match a single character:

Any character that is not a special character (to be defined) matches itself.

  1. A backslash (\) followed by any special character matches the literal character itself; that is, this "escapes" the special character.

  2. The "special characters" are:
    + * ? . [ ] ^ $ ( ) { } | \

  3. The period (.) matches any character. E.g., ".umpty" matches either "Humpty" or "Dumpty."

  4. A set of characters enclosed in brackets ([]) is a one-character RE that matches any of the characters in that set. E.g., "[akm]" matches either an "a", "k", or "m". A range of characters can be indicated with a dash. E.g., "[a-z]" matches any lower-case letter. However, if the first character of the set is the caret (^), then the RE matches any character except those in the set. It does not match the empty string. Example: [^akm] matches any character except "a", "k", or "m". The caret loses its special meaning if it is not the first character of the set. The following rules can be used to build a multicharacter RE:

  5. Parentheses (( )) group parts of regular expressions together into subexpressions that can be treated as a single unit. For example, (ha)+ matches one or more "ha"'s.

  6. A one-character RE followed by an asterisk (*) matches zero or more occurrences of the RE. Hence, [a-z]* matches zero or more lower-case characters.

  7. A one-character RE followed by a plus (+) matches one or more occurrences of the RE. Hence, [a-z]+ matches one or more lower-case characters.

  8. A question mark (?) is an optional element. The preceeding RE can occur zero or once in the string — no more. E.g. xy?z matches either xyz or xz.

  9. The concatenation of REs is a RE that matches the corresponding concatenation of strings. E.g., [A-Z][a-z]* matches any capitalized word.

  10. The OR character ( | ) allows a choice between two regular expressions. For example, jell(y|ies) matches either "jelly" or "jellies".

  11. Braces ({ }) are reserved for future use.

  12. All or part of the regular expression can be "anchored" to either the beginning or end of the string being searched:

  13. If the caret (^) is at the beginning of the (sub)expression, then the matched string must be at the beginning of the string being searched.

  14. If the dollar sign ($) is at the end of the (sub)expression, then the matched string must be at the end of the string being searched.

Persistence

None

Example

#include <rw/re.h>
#include <rw/cstring.h>
#include <rw/rstream.h>
 
main(){
  RWCString aString("Hark! Hark! the lark");
 
  // A regular expression matching any lowercase word or end of a  
  //word starting with "l":
     RWCRExpr re("l[a-z]*");
 
  cout << aString(re) << endl;  // Prints "lark"
}

Public Constructors

RWCRExpr(const char* pat); RWCRExpr(const RWCString& pat);

Construct a regular expression from the pattern given by pat. The status of the results can be found by using member function status().

RWCRExpr(const RWCRExpr& r);

Copy constructor. Uses value semantics — self will be a copy of r.

RWCRExpr();

Default constructor. You must assign a pattern to the regular expression before you use it.

RWCRExpr();

Destructor. Releases any allocated memory.

RWCRExpr& operator=(const RWCRExpr& r);

Recompiles self to pattern found in r.

RWCRExpr& operator=(const char* pat); RWCRExpr& operator=(const RWCString& pat);

Recompiles self to the pattern given by pat. The status of the results can be found by using member function status().

size_t index(const RWCString& str, size_t* len = NULL, size_t start=0) const;

Returns the index of the first instance in the string str that matches the regular expression compiled in self, or RW_NPOS if there is no such match. The search starts at index start. The length of the matching pattern is returned in the variable pointed to by len. If an invalid regular expression is used for the search, an exception of type RWInternalErr will be thrown. Note that this member function is relatively clumsy to use — class RWCString offers a better interface to regular expression searches.

statusType status() const;

Returns the status of the regular expression:

Table 2-2. RWCRExpr command line regular expression status

statusType

Meaning

RWCRExpr::OK

No errors

RWCRExpr::NOT_SUPPORTED

POSIX.2 feature not yet supported.

RWCRExpr::NO_MATCH

Tried to find a match but failed

RWCRExpr::BAD_PATTERN

Pattern was illegal

RWCRExpr::BAD_COLLATING_ELEMENT

Invalid collating element referenced

RWCRExpr::BAD_CHAR_CLASS_TYPE

Invalid character class type referenced

RWCRExpr::TRAILING_BACKSLASH

Trailing \ in pattern

RWCRExpr::UNMATCHED_BRACKET

[] imbalance

RWCRExpr::UNMATCHED_PARENTHESIS

() imbalance

RWCRExpr::UNMATCHED_BRACE

{} imbalance

RWCRExpr::BAD_BRACE

Content of {} invalid.

RWCRExpr::BAD_CHAR_RANGE

Invalid endpoint in [a-z] expression

RWCRExpr::OUT_OF_MEMORY

Out of memory

RWCRExpr::BAD_REPEAT

?,* or + not preceded by valid regular expression




[2] See the section in the User's Guide entitled "RWStringID" for more information on how to make a non-virtual function act like a virtual function.