Tools.h++ Class Library Reference
Cover

Tools.h++ Class Library Reference


SunSoft, Inc.
A Sun Microsystems, Inc. Business
2550 Garcia Avenue
Mountain View, CA 94043 USA
415 960-1300
fax 415 969-9131
Part No.: 802-6441-10
Revision A, December 1996
Copyright
Copyright 1996 Sun Microsystems, Inc., 2550 Garcia Avenue, Mountain View, California 94043-1100 U.S.A. All rights reserved.
This product or document is protected by copyright and distributed under licenses restricting its use, copying, distribution, and decompilation. No part of this product or document may be reproduced in any form by any means without prior written authorization of Sun and its licensors, if any.
Portions of this product may be derived from the UNIX(R) system, licensed from Novell, Inc., and from the Berkeley 4.3 BSD system, licensed from the University of California. UNIX is a registered trademark in the United States and other countries and is exclusively licensed by X/Open Company Ltd. Third-party software, including font technology in this product, is protected by copyright and licensed from Sun's suppliers.
RESTRICTED RIGHTS: Use, duplication, or disclosure by the U.S. Government is subject to restrictions of FAR 52.227- 14(g)(2)(6/87) and FAR 52.227-19(6/87), or DFAR 252.227-7015(b)(6/95) and DFAR 227.7202-3(a).
Sun, Sun Microsystems, the Sun logo, SunSoft, Solaris, Sun WorkShop, Sun Performance WorkShop, Sun Performance Library, Sun Visual WorkShop, and Sun WorkShop TeamWare, are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC International, Inc. in the United States and other countries. Products bearing SPARC trademarks are based upon an architecture developed by Sun Microsystems, Inc. Rogue Wave and .h++ are registered trademarks, and Tools.h++ is a trademark of Rogue Wave Software, Inc.
The OPEN LOOK(R) and Sun(TM) Graphical User Interfaces were developed by Sun Microsystems, Inc. for its users and licensees. Sun acknowledges the pioneering efforts of Xerox in researching and developing the concept of visual or graphical user interfaces for the computer industry. Sun holds a non-exclusive license from Xerox to the Xerox Graphical User Interface, which license also covers Sun's licensees who implement OPEN LOOK GUIs and otherwise comply with Sun's written license agreements.
THIS PUBLICATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
Contents

............................Contents


1. Class Hierarchy
1

2. Class Reference
7
..RWAuditStreamBuffer 7
..RWBag 12
..RWBagIterator 16
..RWBench 18
..RWBinaryTree 25
..RWBinaryTreeIterator 29
..RWbistream 31
..RWBitVec 37
..RWbostream 43
..RWBTree 49
..RWBTreeDictionary 53
..RWBTreeOnDisk 59
..RWBufferedPageHeap 65
..RWCacheManager 67
..RWCLIPstreambuf 69
..RWCollectable 73
..RWCollectableAssociation 77
..RWCollectableDate 79
..RWCollectableInt 81
..RWCollectableString 83
..RWCollectableTime 86
..RWCollection 87
..RWCRegexp 92
..RWCRExpr 96
..RWCString 100
..RWCSubString 118
..RWCTokenizer 122
..RWDate 124
..RWDDEstreambuf 134
..RWDiskPageHeap 139
..RWDlistCollectables 142
..RWDlistCollectablesIterator 147
..RWeistream 150
..RWeostream 157
..RWFactory 162
..RWFile 166
..RWFileManager 171
..RWGBitVec(size) 173
..RWGDlist(type) 177
..RWGDlistIterator(type) 182
..RWGOrderedVector(val) 185
..RWGQueue(type) 190
..RWGSlist(type) 192
..RWGSlistIterator(type) 196
..RWGSortedVector(val) 199
..RWGStack(type) 203
..RWGVector(val) 205
..RWHashDictionary 209
..RWHashDictionaryIterator 214
..rw_hashmap 216
..rw_hashmultimap 223
..rw_hashmultiset 229
..rw_hashset 235
..RWHashTable 241
..RWHashTableIterator 246
..RWIdentityDictionary 247
..RWIdentitySet 249
..RWInteger 250
..RWIterator 252
..RWLocale 253
..RWLocaleSnapshot 259
..RWModel 262
..RWModelClient 264
..RWOrdered 265
..RWOrderedIterator 269
..RWpistream 271
..RWpostream 277
..RWSequenceable 284
..RWSet 285
..RWSetIterator 290
..rw_slist<T> 291
..RWSlistCollectables 297
..RWSlistCollectablesIterator 301
..RWSlistCollectablesQueue 304
..RWSlistCollectablesStack 307
..RWSortedVector 310
..RWTBitVec<size> 314
..RWTime 318
..RWTimer 325
..RWTIsvDlist<T> 328
..RWTIsvDlistIterator<T> 333
..RWTIsvSlist<T> 336
..RWTIsvSlistIterator<T> 341
..RWTPtrDeque<T> 343
..RWTPtrDlist<T> 354
..RWTPtrDlistIterator<T> 365
..RWTPtrHashDictionary 369
..RWTPtrHashDictionaryIterator 370
..RWTPtrHashMap<K,T,H,EQ> 370
..RWTPtrHashMapIterator<K,T,H,EQ> 379
..RWTPtrHashMultiMap<K,T,H,EQ> 382
..RWTPtrHashMultiMapIterator<K,T,H,EQ> 390
..RWTPtrHashMultiSet<T,H,EQ> 393
..RWTPtrHashMultiSetIterator<T,H,EQ> 402
..RWTPtrHashSet<T,H,EQ> 405
..RWTPtrHashSetIterator<T,H,EQ> 413
..RWTPtrHashTable 417
..RWTPtrHashTableIterator 417
..RWTPtrMap<K,T,C> 417
..RWTPtrMapIterator<K,T,C> 426
..RWTPtrMultiMap<K,T,C> 429
..RWTPtrMultiMapIterator<K,T,C> 437
..RWTPtrMultiSet<T,C> 441
..RWTPtrMultiSetIterator<T,C> 448
..RWTPtrOrderedVector<T> 451
..RWTPtrSet<T,C> 461
..RWTPtrSetIterator<T,C> 469
..RWTPtrSlist<T> 472
..RWTPtrSlistIterator<T> 482
..RWTPtrSortedDlist<T,C> 486
..RWTPtrSortedDlistIterator<T,C> 495
..RWTPtrSortedVector<T,C> 499
..RWTPtrVector<T> 508
..RWTQueue<T,C> 511
..RWTStack<T,C> 513
..RWTValDeque<T> 515
..RWTValDlist<T> 526
..RWTValDlistIterator<T> 536
..RWTValHashDictionary 541
..RWTValHashDictionaryIterator 541
..RWTValHashMap<K,T,H,EQ> 542
..RWTValHashMapIterator<K,T,H,EQ> 549
..RWTValHashMultiMap<K,T,H,EQ> 552
..RWTValHashMultiMapIterator<K,T,H,EQ> 560
..RWTValHashMultiSet<T,H,EQ> 563
..RWTValHashMultiSetIterator<T,H,EQ> 571
..RWTValHashSet<T,H,EQ> 574
..RWTValHashSetIterator<T,H,EQ> 583
..RWTValHashTable 586
..RWTValHashTableIterator 586
..RWTValMap<K,T,C> 586
..RWTValMapIterator<K,T,C> 594
..RWTValMultiMap<K,T,C> 598
..RWTValMultiMapIterator<K,T,C> 606
..RWTValMultiSet<T,C> 609
..RWTValMultiSetIterator<T,C> 616
..RWTValOrderedVector<T> 619
..RWTValSet<T,C> 628
..RWTValSetIterator<T,C> 636
..RWTValSlist<T> 639
..RWTValSlistIterator<T> 648
..RWTValSortedDlist<T,C> 653
..RWTValSortedDlistIterator<T,C> 661
..RWTValSortedVector<T,C> 666
..RWTValVector<T> 675
..RWTValVirtualArray<T> 678
..RWVirtualPageHeap 683
..RWvios 686
..RWvistream 688
..RWvostream 693
..RWWString 698
..RWWSubString 714
..RWWTokenizer 718
..RWXDRistream (Unix only) 720
..RWXDRostream (Unix only) 726
..RWZone 732
..RWZoneSimple 736

A. Alternate Template Class Interfaces
743
..RWTPtrDlist<T> 743
..RWTPtrDlistIterator<T> 752
..RWTPtrHashDictionary<K,V> 755
..RWTPtrHashDictionaryIterator<K,V> 760
..RWTPtrHashSet<T> 762
..RWTPtrHashTable<T> 766
..RWTPtrHashTableIterator<T> 770
..RWTPtrOrderedVector<T> 772
..RWTPtrSlist<T> 778
..RWTPtrSlistIterator<T> 786
..RWTPtrSortedVector<T> 789
..RWTValDlist<T> 795
..RWTValDlistIterator<T> 803
..RWTValHashDictionary<K,V> 807
..RWTValHashDictionaryIterator<K,V> 811
..RWTValHashSet<T> 813
..RWTValHashTable<T> 817
..RWTValHashTableIterator<T> 821
..RWTValOrderedVector<T> 823
..RWTValSlist<T> 829
..RWTValSlistIterator<T> 837
..RWTValSortedVector<T> 840
Introduction

Introduction

The Tools.h++ Class Reference describes all the classes and functions in Tools.h++. It does not provide a tutorial on how to program with the Tools.h++ class library. For information on how to write programs using Tools.h++, consult the Tools.h++ User's Guide. For information on installing and using Tools.h++, review the Tools.h++ Getting Started Guide.

Organization of the Class Reference

Immediately following this introduction is a class hierarchy diagram. The class hierarchy lists all the classes, and illustrates the relationships among them. You can refer to it for a bird's-eye view of the inheritance structure used in Tools.h++.
The remainder of this reference is an alphabetical listing of classes. The entry for each class begins with an illustration showing the individual class's inheritance hierarchy, followed by a synopsis that lists the header files(s) and the Smalltalk typedef (if appropriate) associated with the class. The synopsis also shows a declaration and definition of a Class object, and any typedefs that are used. Following the synopsis is a brief description of the class, and a list of member and global functions. These functions are organized in categories according to their general use - for example, "constructors," "global operators," and "public member functions." The categories, although somewhat arbitrary, provide a way of organizing the many functions.

Conventions

All Rogue Wave class names start with the letters RW, as in RWCollectable, with the bold font emphasizing the class name rather than the prefix. In some cases, we may refer to an instance of a class by an English name; for example, "the string" instead of "the RWCString instance." We do this to make it easier to read when the meaning should be clear from context, but we use the longer form if there is a possible ambiguity.
All function names begin with a lower case letter, with the first letter of subsequent words capitalized. Function names attempt to accurately describe what a function does. For example, RWCString::toLower() changes all uppercase letters in itself to lowercase. Underline characters and abbreviations are not generally used in function names.
Function names, examples, operating system commands, mathematical symbols and code fragments are shown in a courier font, as in <rw/stream.h>. Vertical ellipses are used in code examples to indicate that some part of the code is missing.
Throughout this documentation, there are frequent references to "self." This should be read as "*this".

Inheritance Notation

Each class that inherits from another class (or other classes) includes an illustration that shows the inheritance hierarchy. For example, the following illustration indicates that class A inherits from class B:

Internal bitmap(127x31)

When a class inherits from more than one class, or there are multiple levels of inheritance, all of the inheritance relationships are shown. For example, the following illustration indicates that A inherits from class B and from class C, which inherits from class D.

Internal bitmap(145x59)

The notation system used in the inheritance hierarchies is based on the Object 1 Modeling Technique (OMT) developed by Rumbaugh and others.

Member Functions

Within their general categories, member functions for each class are listed alphabetically. Member functions fall into three general types:
  1. Functions that are unique to a class. The complete documentation for these functions is presented in the class where they occur. An example is balance(), a member of the class RWBinaryTree.

  2. Functions that are inherited from a base class without being redefined. The complete documentation for these functions is presented in the defining base class. An example is clearAndDestroy(), for class RWBinaryTree, which is inherited from class RWCollection. When a member function is inherited without being redefined, the member function appears in both places, and this guide refers you to the original definition.

  3. Functions that are redefined in a derived class. These are usually virtual functions. The documentation for these functions usually directs you to the base class, but may also mention peculiarities that are relevant to the derived class. An example is apply(), for class RWBinaryTree.



1. The notation is similar to the notation used in Design Patterns by Gamma, Helm, Johnson, and Vlissides.
1 Class Hierarchy

Class Hierarchy

1

The following list shows the public class hierarchy of the Tools.h++ classes. Note that this is the public class hierarchy--the implementation of a given class may use private inheritance. Additionally, some classes inherit from public, but undocumented, implementation classes. Undocumented classes are omitted from the hierarchy.
Classes derived by multiple inheritance show their additional base(s) in italics to the right of the class name.

Class Hierarchy

RWBench
RWBitVec
RWBTreeOnDisk
RWCacheManager
RWCollectable
RWCollection
RWBag
RWBinaryTree
RWBTree
RWBTreeDictionary
RWHashTable
RWSet
RWFactory
RWHashDictionary
RWIdentityDictionary
RWIdentitySet
RWSequenceable
RWDlistCollectables
RWOrdered
RWSortedVector
RWSlistCollectables
RWSlistCollectablesQueue
RWSlistCollectablesStack
RWCollectableAssociation
RWCollectableDate (&RWDate)
RWCollectableInt (&RWInteger)
RWCollectableString (&RWCString)
RWCollectableTime (&RWTime)
RWModelClient
RWCRegexp
RWCRExp
RWCString
RWCollectableString (&RWCollectable)
RWCSubString
RWCTokenizer
RWDate
RWCollectableDate (&RWCollectable)
RWErrObject
RWFactory
RWFile
RWFileManager
RWGBitVec(size)
RWGDlist(type)
RWGDlistIterator(type)
RWGOrderedVector(val)
RWGQueue(type)
RWGSlist(type)
RWGSlistIterator(type)
RWGStack(type)
RWGVector(val)
RWGSortedVector(val)
RWInstanceManager
RWInteger
RWCollectableInt (&RWCollectable)
RWIterator
RWBagIterator
RWBinaryTreeIterator
RWDlistCollectablesIterator
RWHashDictionaryIterator
RWHashTableIterator
RWSetIterator
RWOrderedIterator
RWSlistCollectablesIterator
RWLocale
RWLocaleSnapshot
RWMessage
RWModel
RWReference
RWCStringRef
RWVirtualRef
RWWStringRef
RWTime
RWCollectableTime (&RWCollectable)
RWTimer
RWTBitVec<size>
RWTIsvDlist<T>
RWTIsvDlistIterator<TL>
RWTIsvSlist<T>
RWTIsvSlistIterator<TL>
RWTPtrDeque<T>
RWTPtrDlist<T>
RWTPtrDlistIterator<T>
RWTPtrHashMap<Key,Type,Hash,EQ>
RWTPtrHashMapIterator<Key,Type,Hash,EQ>
RWTPtrHashMultiMap<Key,Type,Hash,EQ>
RWTPtrHashMultiMapIterator<Key,Type,Hash,EQ>
RWTPtrHashMultiSet<T,Hash,EQ>
RWTPtrHashMultiSetIterator<T,Hash,EQ>
RWTPtrHashSet<T,Hash,EQ>
RWTPtrHashSetIterator<T,Hash,EQ>
RWTPtrMap<Key,Type,Compare>
RWTPtrMapIterator<Key,Type,Compare>
RWTPtrMultiMap<Key,Type,Compare>
RWTPtrMultiMapIterator<Key,Type,Compare>
RWTPtrMultiSet<T,Compare>
RWTPtrMultiSetIterator<T,Compare>
RWTPtrOrderedVector<T>
RWTPtrSet<T,Compare>
RWTPtrSetIterator<T,Compare>
RWTPtrSlist<T>
RWTPtrSlistIterator<T>
RWTPtrSlistDictionary<KeyP,ValP>
RWTPtrSlistDictionaryIterator<KeyP,ValP>
RWTPtrSortedDlist<T,Compare>
RWTPtrSortedDlistIterator<T,Compare>
RWTPtrSortedVector<T,Compare>
RWTPtrVector<T>
RWTQueue<T,Container>
RWTRegularExpression<charT>
RWTStack<T,Container>
RWTValDeque<T>
RWTValDlist<T>
RWTValDlistIterator<T>
RWTValHashMap<Key,Type,Hash,EQ>
RWTValHashMapIterator<Key,Type,Hash,EQ>
RWTValHashMultiMap<Key,Type,Hash,EQ>
RWTValHashMultiMapIterator<Key,Type,Hash,EQ>
RWTValHashMultiSet<T,Hash,EQ>
RWTValHashMultiSetIterator<T,Hash,EQ>
RWTValHashSet<T,Hash,EQ>
RWTValHashSetIterator<T,Hash,EQ>
RWTValMap<Key,Type,Compare>
RWTValMapIterator<Key,Type,Compare>
RWTValMultiMap<Key,Type,Compare>
RWTValMultiMapIterator<Key,Type,Compare>
RWTValMultiSet<T,Compare>
RWTValMultiSetIterator<T,Compare>
RWTValOrderedVector<T>
RWTValSet<T,C>
RWTValSetIterator<T,C>
RWTValSlist<T>
RWTValSlistIterator<T>
RWTValSlistDictionary<Key,V>
RWTValSlistDictionaryIterator<Key,V>
RWTValSortedDlist<T,Compare>
RWTValSortedDlistIterator<T,Compare>
RWTValSortedVector<T>
RWTValVector<T>
RWTValVirtualArray<T>
RWvios
RWios (virtual)
RWvistream
RWbistream (&ios: virtual)
RWeistream
RWpistream
RWXDRistream (&RWios)
RWvostream
RWbostream (&ios: virtual)
RWeostream
RWpostream
RWXDRostream (&RWios)
RWVirtualPageHeap
RWBufferedPageHeap
RWDiskPageHeap
RWWString
RWWSubString
RWWTokenizer
RWZone
RWZoneSimple
streambuf
RWAuditStreamBuffer
RWCLIPstreambuf
RWDDEstreambuf
xmsg
RWxmsg
RWExternalErr
RWFileErr
RWStreamErr
RWInternalErr
RWBoundsErr
RWxalloc
2 Class Reference

Class Reference

2

RWAuditStreamBuffer

RWAuditStreamBuffer

RWAuditStreamBuffer . streambuf

Synopsis

#include <rw/auditbuf.h>
#include <iostream.h>
RWAuditStreamBuffer buf(arguments)
ostream os(&buf); // may be used for ostreams
istream is(&buf); // or istreams of any kind

Description

Class RWAuditStreamBuffer is used to construct a stream, after which the RWAuditStreamBuffer instance will count all the bytes that pass through the stream. If constructed with a function pointer, RWAuditStreamBuffer will call that function with each byte that passes through the stream. The counting capacity provides for streams the equivalent of the RWCollectable method recursiveStoreSize() which is only available for RWFile.

Persistence

None

Short Example


  #include <rw/auditbuf.h>  
  #include <rw/bstream.h>  
  #include <rw/pstream.h>  
  #include <iostream.h>  
  int main() {  
    RWCollectable ct;  
    fillCollectable();  // make a collection, somehow  
    RWAuditStreamBuffer bcounter, pcounter;  
    RWbostream bcount(&bcounter); //ctor takes streambuf pointer  
    RWpostream pcount(&pcounter);  
  //...  
    bcount << ct;  
    pcount << ct;  
  cout  << "We just counted " << bcounter  
        << " bytes from an RWbostream." << endl;  
  cout  << "We just counted " << pcounter  
        << " bytes from an RWpostream." << endl;  
  return 0;  
  }  

Related Classes

RWAuditStreamBuffer may be used as the streambuf for any stream, including those derived from RWvostream or RWvistream, strstream, ifstream, ofstream, etc.

Global Typedef

typedef void (*RWauditFunction)(unsigned char, void*);
If you wish to do more than count each character handled by the buffer, you may provide an RWauditFunction to the constructor. The first parameter to this function is a byte provided by the stream. The second parameter is the address of the conter to be manipulated by RWAuditFunction.

Public Constructors

RWAuditStreamBuffer(RWauditFunction=0, void*=0);
Constructs a new RWAuditStreamBuffer that may be used only to examine and count every byte that passes into an ostream that has the RWAuditStreamBuffer instance as its streambuf. It will not forward the bytes to any stream, nor accept bytes from a stream. The second argument to the constructor allows you to supply storage for the byte count. It is optional.
RWAuditStreamBuffer(istream&, RWauditFunction=0, void*=0);
Constructs a new RWAuditStreamBuffer that passes bytes from the istream on which it is constructed to the istream that has the RWAuditStreamBuffer instance as its streambuf. A typical use would be to count or examine the bytes being input from a file through a stream derived from RWvistream. The second argument to the constructor allows you to supply storage for the byte count. It is optional.
RWAuditStreamBuffer(iostream&, RWauditFunction=0, void*=0);
Constructs a new RWAuditStreamBuffer that passes bytes to and from the iostream on which it is constructed to and from the istream that has the RWAuditStreamBuffer instance as its streambuf. A typical use would be to count or examine the bytes being transferred to and from a file used to store and retrieve changing data. The second argument to the constructor allows you to supply storage for the byte count. It is optional.
RWAuditStreamBuffer(ostream&, RWauditFunction=0, void*=0);
Constructs a new RWAuditStreamBuffer that passes bytes into the ostream on which it is constructed from the ostream that has the RWAuditStreamBuffer instance as its streambuf. A typical use would be to count or examine the bytes being output to a file through a stream derived from RWvostream. The second argument to the constructor allows you to supply storage for the byte count. It is optional.
RWAuditStreamBuffer(streambuf*, RWauditFunction=0, void*=0);
Constructs a new RWAuditStreamBuffer that passes bytes into the ostream on which it is constructed from the ostream that has the RWAuditStreamBuffer instance as its streambuf. A typical use would be to count or examine the bytes being output to a file through a stream derived from RWvostream. The second argument to the constructor allows you to supply storage for the byte count. It is optional.

Public Destructor

virtual ~RWAuditStreamBuffer();
We have provided an empty destructor since some compilers complain if there is no virtual destructor for a class that has virtual methods.

Public Member Operator

operator unsigned long();
Provides the count of bytes seen so far.

Public Member Function

unsigned long
reset(unsigned long value = 0);
Resets the count of bytes seen so far. Returns the current count.

Extended Example


  #include <iostream.h>  
  #include <fstream.h>  
  #include <rw/auditbuf.h>  
  #include <rw/pstream.h>  
  #include <rw/cstring.h>  
  void doCrc (unsigned char c, void* x) {  
    *(unsigned char*)x ^= c;  
  }  
  
  int main() {  
  if(1) { // just a block to control variable lifetime  
      unsigned char check = '\0';  
  
      // create an output stream  
      ofstream                            op("crc.pst");  

      // create an RWAuditStreamBuffer that will do CRC  
      RWAuditStreamBuffer               crcb(op,doCrc,&check);  
      // create an RWpostream to put the data through.  
  RWpostream                           p(&crcb);  
  
      // now send some random stuff to the stream  
      p << RWCString("The value of Tools.h++ is at least ");  
      p << (int)4;  
      p << RWCString(" times that of the next best library!\n") ;  
      p << RWCString("Pi is about ") << (double)3.14159 << '.';  
  
      // finally, save the sum on the stream itself.  
  p << (unsigned int)check; // alters check, _after_ saving it...  
  
      // just for fun, print out some statistics:  
      cout << "We just saved " << crcb  
           << " bytes of data to the file." << endl;  
      cout << "The checksum for those bytes was " <<check << endl;  
  } // end of block  
  
    // now read the data back in, checking to see if it survived.  
    unsigned char check = '\0';  
  
    // create an instream  
    ifstream                            ip("crc.pst");  
  
    // create an RWAuditStreamBuffer that will do CRC  
    RWAuditStreamBuffer               crcb(ip,doCrc,&check);  
  
    // create an RWpistream to interpret the bytes  
    RWpistream                           p(&crcb);  
  
    RWCString first, mid1, mid2;  
    int value;  
    double pi;  
    char pnc;  
    unsigned int savedCRC;  
    unsigned char matchCRC;  
    // read in the data. Don\'t read the checksum yet!  
    p >> first >> value >> mid1 >> mid2 >> pi >> pnc;  
    // save the checksum  
    matchCRC = check;  

    // Now it is safe to alter the running checksum by reading in  
    // the one saved in the file.  
  p >> savedCRC;  
    if(savedCRC != matchCRC) {  
      cout << "Checksum error. Saved CRC: " << savedCRC  
           << " built CRC: " << matchCRC << dec << endl;  
    }  
    else {  
      cout << "The message was: " << endl;  
      cout << first << value << mid1 << mid2 << pi << pnc << endl;  
    }  
    // just for fun, print out some statistics:  
    cout  << "We just read " << crcb  
          << " bytes of data from the file." << endl;  
    cout  << "The checksum was " << matchCRC << flush;  
    cout  << " and the saved checksum was " << savedCRC << endl;  
  return 0;  
  }  
RWBag

RWBag

RWBag . RWCollection . RWCollectable

Synopsis

typedef RWBag Bag;     // Smalltalk typedef .
#include <rw/rwbag.h>
RWBag h;

Description

Class RWBag corresponds to the Smalltalk class Bag. It represents a group of unordered elements, not accessible by an external key. Duplicates are allowed.
An object stored by RWBag must inherit abstract base class RWCollectable, with suitable definition for virtual functions hash() and isEqual() (see class RWCollectable). The function hash() is used to find objects with the same hash value, then isEqual() is used to confirm the match.
Class RWBag is implemented by using an internal hashed dictionary (RWHashDictionary) which keeps track of the number of occurrences of an item. If an item is added to the collection that compares equal (isEqual) to an existing item in the collection, then the count is incremented. Note that this means that only the first instance of a value is actually inserted: subsequent instances cause the occurrence count to be incremented. This behavior parallels the Smalltalk implementation of Bag.
Member function apply() and the iterator are called repeatedly according to the count for an item.
See class RWHashTable if you want duplicates to be stored, rather than merely counted.

Persistence

Polymorphic

Public Constructors

RWBag(size_t n = RWDEFAULT_CAPACITY);
Construct an empty bag with n buckets.
RWBag(const RWBag& b);
Copy constructor. A shallow copy of b will be made.

Public Member Operators

void
operator=(const RWBag& b);
Assignment operator. A shallow copy of b will be made.
RWBoolean
operator==(const RWBag& b) const;
Returns TRUE if self and bag b have the same number of total entries and if for every key in self there is a corresponding key in b which isEqual and which has the same number of entries.

Public Member Functions

virtual void
apply(RWapplyCollectable ap, void*);
Redefined from class RWCollection. This function has been redefined to apply the user-supplied function pointed to by ap to each member of the collection in a generally unpredictable order. If an item has been inserted more than once (i.e., more than one item isEqual), then apply() will be called that many times. The user-supplied function should not do anything that could change the hash value or the meaning of "isEqual" of the items.
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 was inserted into the Bag and which equals target is returned or nil if no item is found. Hashing is used to narrow the search.
virtual unsigned
hash() const;
Inherited from class RWCollectable.
virtual RWCollectable*
insert(RWCollectable* c);
Redefined from class RWCollection. Inserts the item c into the collection and returns it, or if an item was already in the collection that isEqual to c, then returns the old item and increments its count.
RWCollectable*
insertWithOccurrences(RWCollectable* c,size_t n);
Inserts the item c into the collection with count n and returns it, or if an item was already in the collection that isEqual to c, then returns the old item and increments its count by n.
virtual RWClassID
isA() const;
Redefined from class RWCollectable to return __RWBAG.
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 are equal to the item pointed to by target.
virtual RWCollectable*
remove(const RWCollectable* target);
Redefined from class RWCollection. Removes and returns the item that isEqual to the item pointed to by target. Returns nil if no item was found.
virtual void
removeAndDestroy(const RWCollectable* target);
Redefined from class RWCollection. Removes the item that isEqual to the item pointed to by target. Destroys the item as well if it is the last occurrence in the collection.
void
resize(size_t n = 0);
Resizes the internal hash table to have n buckets. The overhead for this function is the hashing of every element in the collection. If n is zero, then an appropriate size will be picked automatically.
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.
RWBagIterator

RWBagIterator

RWBagIterator . RWIterator

Synopsis

#include <rw/rwbag.h>
RWBag b;
RWBagIterator it(b);

Description

Iterator for class RWBag, which allows sequential access to all the elements of RWBag. Note that because an RWBag is unordered, elements are not accessed in any particular order. If an item was inserted N times into the collection, then it will be visited N consecutive times.
Like all Rogue Wave iterators, the "current item" is undefined immediately after construction -- you must define it by using operator() or some other (valid) operation.
Once the iterator has advanced beyond the end of the collection it is no longer valid -- continuing to use it will bring undefined results.

Persistence

None

Public Constructor

RWBagIterator(const RWBag&);
Construct an iterator for an RWBag. After construction, the position of the iterator is undefined.

Public Member Operator

virtual RWCollectable*
operator()();
Redefined from class RWIterator. Advances the iterator to the next item and returns it. Returns nil when the end of the collection has been reached.

Public Member Functions

virtual RWCollectable*
findNext(const RWCollectable* target);
Redefined from class RWIterator. Moves iterator to the next item which isEqual to the object pointed to by target and returns it. Hashing is used to find the target. If no item is found, returns nil and the position of the iterator will be undefined.
virtual RWCollectable*
key() const;
Redefined from class RWIterator. Returns the item at the current iterator position.
virtual void
reset();
Redefined from class RWIterator. Resets the iterator to its starting state.
RWBench

RWBench

Synopsis

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

Description

This is an abstract class that can automate the process of benchmarking a piece of code. To use it, derive a class from RWBench, including a definition for the virtual function doLoop(unsigned long N). This function should perform N operations of the type that you are trying to benchmark. RWBench will call doLoop() over and over again until a preset amount of time has elapsed. It will then sum the total number of operations performed.
To run, construct an instance of your derived class and then call go(). Then call report() to get a standard summary. For many compilers, this summary will automatically include the compiler type and memory model. You can call ops(), outerLoops(), etc. for more detail.
If you wish to correct for overhead, then provide an idleLoop() function which should do all non-benchmark-related calculations.

Persistence

None

Example

This example benchmarks the time required to return a hash value for a Rogue Wave string versus a Borland string.

  #include <rw/bench.h>                 /* Benchmark software */  
  #include <rw/cstring.h>               /* Rogue Wave string class */  
  #include <stdlib.h>  

  #include <iostream.h>  
  #include <rw/ctoken.h>  
  #include <rw/regexp.h>  
  
  // The string to be hashed:  
  const char* cs = "A multi-character string with lots of words in  
  it to be parsed out and searched for.";  
  
  class TestBrute : public RWBench {  
  public:  
  TestBrute() { }  
    virtual void       doLoop(unsigned long n);  
    virtual void       idleLoop(unsigned long n);  
    virtual void       what(ostream& s) const  
      { s << "Brute force string search: \n"; }  
  };  
  
  class TestRW : public RWBench {  
  public:  
  TestRW() { }  
    virtual void     doLoop(unsigned long n);  
    virtual void       idleLoop(unsigned long n);  
    virtual void       what(ostream& s) const  
      { s << "Rogue Wave search: \n"; }  
  };  
  
  main(int argc, char* argv[]){  
    cout << "Testing string \n\"" << cs << "\"\n";  
  
    // Test brute force string search algorithm:  
    TestBrute other;  
    other.parse(argc, argv);  
    other.go();  
    other.report(cout);  
  
    // Test RW searching w/regular expressions:  
    TestRW rw;  
    rw.parse(argc, argv);  
    rw.go();  
    rw.report(cout);  
  
    return 0;  
  }  

  void TestBrute::doLoop(unsigned long n){  
    RWCString string(cs);  
    RWCTokenizer *tokener;  
    RWCString token;  
  
    tokener = new RWCTokenizer(string);  
  
    while(n--){  
  
      if((token = (*tokener)()).isNull())  
      {  
          delete tokener;  
          tokener = new RWCTokenizer(string);  
          token = (*tokener)();  
      }  
  
      size_t j = 0;  
  
      for(size_t i = 0; i < string.length() && j != token.length();  
          i++)  
      {  
         j = 0;  
         while((j < token.length()) && (string[i+j]==token[j]))  
            j++;  
      }  
  
    }  
   delete tokener;  
  }  
  
  void TestRW::doLoop(unsigned long n){  
    RWCString string(cs);  
    RWCTokenizer *tokener;  
    RWCString token, result;  
    RWCRegexp re("");  
  
    tokener = new RWCTokenizer(string);  
  
    while(n--){  
  
     if((token = (*tokener)()).isNull())  

      {  
          delete tokener;  
          tokener = new RWCTokenizer(string);  
          token = (*tokener)();  
      }  
  
    re = RWCRegexp(token);  
    result = string(re);       //Do the search!  
  
    }  
   delete tokener;  
  }  
  
  void TestBrute::idleLoop(unsigned long n){  
    RWCString string(cs);           // Subtract out the overhead  
    RWCTokenizer *tokener;  
    RWCString token;  
  
    tokener = new RWCTokenizer(string);  
  
    while(n--){  
  
     if((token = (*tokener)()).isNull())  
      {  
          delete tokener;  
          tokener = new RWCTokenizer(string);  
          token = (*tokener)();  
      }  
  
    }  
   delete tokener;  
  }  
  
  void TestRW::idleLoop(unsigned long n){  
    RWCString string(cs);                //Subtract out the overhead  
    RWCTokenizer *tokener;  
    RWCString token, result;  
    RWCRegexp re("");  
  
    tokener = new RWCTokenizer(string);  
  
    while(n--){  
  
     if((token = (*tokener)()).isNull())  

      {  
          delete tokener;  
          tokener = new RWCTokenizer(string);  
          token = (*tokener)();  
      }  
  
    re = RWCRegexp(token);  
  
    }  
   delete tokener;  
  }  

Program output:


  Testing string  
  "A multi-character string with lots of words in it to be parsed  
  out and searched for."  
  Borland C++ V4.0  
  
  Brute force string search:  
  
  Iterations:                 35  
  Inner loop operations:      1000  
  Total operations:           35000  
  Elapsed (user) time:        4.596  
  Kilo-operations per second: 7.61532  
  
  Borland C++ V4.0  
  
  Rogue Wave search:  
  
  Iterations:                 53  
  Inner loop operations:      1000  
  Total operations:           53000  
  Elapsed (user) time:        2.824  
  Kilo-operations per second: 18.7677  

Public Constructors

RWBench(double duration = 5, unsigned long ILO=1000,
        const char* machine = 0);
The parameter duration is the nominal amount of time that the benchmark should take in seconds. The virtual function doLoop(unsigned long) will be called over and over again until at least this amount of time has elapsed. The parameter ILO is the number of "inner loop operations" that should be performed. This parameter will be passed in as parameter N to doLoop(N). Parameter machine is an optional null terminated string that should describe the test environment (perhaps the hardware the benchmark is being run on ).

Public Member Functions

virtual void
doLoop(unsigned long N)=0;
A pure virtual function whose actual definition should be supplied by the specializing class. This function will be repeatedly called until a time duration has elapsed. It should perform the operation to be benchmarked N times. See the example.
double
duration() const;
Return the current setting for the benchmark test duration. This should not be confused with function time() which returns the actual test time.
virtual void
go();
Call this function to run the benchmark.
virtual void
idleLoop(unsigned long N);
This function can help to correct the benchmark for overhead. The default definition merely executes a "for()" loop N times. See the example.
const char *
machine();
This function accesses the name of the machine which is passed into the benchmark object through parse().
virtual void
parse(int argc, char* argv[]);
This function allows an easy way to change the test duration, number of inner loops and machine description from the command line:
ArgumentTypeDescription
argv[1]doubleDuration (sec.)
argv[2]unsigned longNo. of inner loops
argv[3]const char*Machine
void
parse(const char *);
This is a non-virtual function which provides the same service as parse(int argc, char * argv[]), but is designed for Windows users. It extracts tokens from the null-terminated command argument provided by Windows, then calls the virtual parse for ANSI C command arguments.
virtual void
report(ostream&) const;
Calling this function provides an easy and convenient way of getting an overall summary of the results of a benchmark.
double
setDuration(double t);
Change the test duration to time t.
unsigned long
setInnerLoops(unsigned long N);
Change the number of "inner loop operations" to N.
virtual void
what(ostream&) const;
You can supply a specializing version of this virtual function that provides some detail of what is being benchmarked. It is called by report() when generating a standard report.
void
where(ostream&) const;
This function will print information to the stream about the compiler and memory model that the code was compiled under.
unsigned long
innerLoops() const;
Returns the current setting for the number of inner loop operations that will be passed into function doLoop(unsigned long N) as parameter N.
double
time() const;
Returns the amount of time the benchmark took, corrected for overhead.
unsigned long
outerLoops() const;
Returns the number of times the function doLoop() was called.
double
ops() const;
Returns the total number of inner loop operations that were performed (the product of the number of times outerLoop() was called times the number of inner loop operations performed per call).
double
opsRate() const;
Returns the number of inner loop operations per second.
RWBinaryTree

RWBinaryTree

RWBinaryTree . RWCollection . RWCollectable

Synopsis

typedef RWBinaryTree SortedCollection;   // Smalltalk typedef.
#include <rw/bintree.h>
RWBinaryTree bt;

Description

Class RWBinaryTree represents a group of ordered elements, internally sorted by the compareTo() function. Duplicates are allowed. An object stored by an RWBinaryTree must inherit abstract base class RWCollectable.

Persistence

Polymorphic

Public Constructors

RWBinaryTree();
Construct an empty sorted collection.
RWBinaryTree(const RWBinaryTree& t);
Copy constructor. Constructs a shallow copy from t. Member function balance() (see below) is called before returning.
virtual ~RWBinaryTree();
Redefined from RWCollection. Calls clear().

Public Member Operators

void
operator=(const RWBinaryTree& bt);
Sets self to a shallow copy of bt.
void
operator+=(const RWCollection ct);
Inserts each element of .ct into self. Note that using this operator to insert an already-sorted collection will result in creating a very unbalanced tree, possibly to the point of stack overflow.
RWBoolean
operator<=(const RWBinaryTree& bt) const;
Returns TRUE if self is a subset of the collection bt. That is, every item in self must compare equal to a unique item in bt.
RWBoolean
operator==(const RWBinaryTree& bt) const;
Returns TRUE if self and bt are equivalent. That is, they must have the same number of items and every item in self must compare equal to a unique item in bt.

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.
void
balance();
Special function to balance the tree. In a perfectly balanced binary tree with no duplicate elements, the number of nodes from the root to any external (leaf) node differs by at most one node. Since this collection allows duplicate elements, a perfectly balanced tree is not always possible. Preserves the order of duplicate elements.
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. Returns the first item that compares equal to the item pointed to by target, or nil if no item was found.
virtual unsigned
hash() const;
Inherited from class RWCollectable.
unsigned
height() const;
Returns the number of nodes between the root node and the farthest leaf. A RWBinaryTree with one entry will have a height of 1. Note that the entire tree is traversed to discover this value.
virtual RWCollectable*
insert(RWCollectable* c);
Redefined from class RWCollection. Inserts the item c into the collection and returns it. Returns nil if the insertion was unsuccessful. The item c is inserted according to the value returned by compareTo(). insert() does not automatically balance the RWBinaryTree. Be careful not to insert() a long sequence of sorted items without calling balance() since the result will be very unbalanced (and therefore inefficient).
virtual RWClassID
isA() const;
Redefined from class RWCollectable to return __RWBINARYTREE.
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 the item pointed to by target.
virtual RWCollectable*
remove(const RWCollectable* target);
Redefined from class RWCollection. Removes the first item that compares equal to the object pointed to by target and returns it. 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&);
Inherited from class RWCollection.
virtual void
saveGuts(RWvostream&) const;
virtual void
saveGuts(RWFile&) const;
Redefined from class RWCollection to store objects by level, rather than in order. This results in the tree maintaining its morphology.
RWStringID
stringID();
(acts virtual) Inherited from class RWCollectable.
RWBinaryTreeIterator

RWBinaryTreeIterator

RWBinaryTreeIterator . RWIterator

Synopsis

// Smalltalk typedef:
typedef RWBinaryTreeIterator SortedCollectionIterator;
#include <rw/bintree.h>
RWBinaryTree bt;
RWBinaryTreeIterator iterate(bt);

Description

Iterator for class RWBinaryTree. Traverses the tree from the "smallest" to "largest" element, where "smallest" and "largest" are defined by the virtual function compareTo(). Note that this approach is generally less efficient than using the member function RWBinaryTree::apply().
Like all Rogue Wave iterators, the "current item" is undefined immediately after construction -- you must define it by using operator() or some other (valid) operation.
Once the iterator has advanced beyond the end of the collection it is no longer valid -- continuing to use it will bring undefined results.

Persistence

None

Public Constructor

RWBinaryTreeIterator(const RWBinaryTree&);
Constructs an iterator for an RWBinaryTree. Immediately after construction, the position of the iterator is undefined until positioned.

Public Member Operator

virtual RWCollectable*
operator()();
Redefined from class RWIterator. Advances iterator to the next "largest" element and returns a pointer to it. Returns nil when the end of the collection is reached.

Public Member Functions

virtual RWCollectable*
findNext(const RWCollectable* target);
Redefined from class RWIterator. Moves iterator to the next item which compares equal to the object pointed to by target and returns it. If no item is found, returns nil and the position of the iterator will be undefined.
virtual void
reset();
Redefined from class RWIterator. Resets iterator to its state at construction.
virtual RWCollectable*
key() const;
Redefined from class RWIterator. Returns the item at the current iterator position.
RWbistream

RWbistream

. RWvistream . RWios . RWvios
RWbistream
. ios

Synopsis

#include <rw/bstream.h>
RWbistream bstr(cin);        // Construct an RWbistream,
                             // using cin's streambuf

Description

Class RWbistream specializes the abstract base class RWvistream to restore variables stored in binary format by RWbostream.
You can think of it as a binary veneer over an associated streambuf. Because the RWbistream retains no information about the state of its associated streambuf, its use can be freely exchanged with other users of the streambuf (such as an istream or ifstream).
RWbistream can be interrogated as to the stream state using member functions good(), bad(), eof(), etc.

Persistence

None

Example

See RWbostream for an example of how the file "data.dat" might be created.

  #include <rw/bstream.h>  
  #include <fstream.h>  
  
  main(){  
    ifstream fstr("data.dat");    // Open an input file  
    RWbistream bstr(fstr);        // Construct RWbistream from it  
  
    int i;  
    float f;  
    double d;  
  
    bstr >> i;         // Restore an int that was stored in binary  
    bstr >> f >> d;    // Restore a float & double  
  }  
  END FILE  

Public Constructors

RWbistream(streambuf* s);
Construct an RWbistream from the streambuf s. For DOS, this streambuf must have been opened in binary mode.
RWbistream(istream& str);
Construct an RWbistream using the streambuf associated with the istream str. For DOS, the streambuf must have been opened in binary mode. This can be done by specifying ios::binary as part of the second argument to the constructor for an ifstream. Using the example above, the line to create the ifstream would read, ifstream fstr("data.dat", ios::in | ios::binary); where the "|" is the binary OR operator.

Public Operators

virtual RWvistream&
operator>>(char& c);
Redefined from class RWvistream. Get the next char from the input stream and store it in c.
virtual RWvistream&
operator>>(wchar_t& wc);
Redefined from class RWvistream. Get the next wide char from the input stream and store it in wc.
virtual RWvistream&
operator>>(double& d);
Redefined from class RWvistream. Get the next double from the input stream and store it in d.
virtual RWvistream&
operator>>(float& f);
Redefined from class RWvistream. Get the next float from the input stream and store it in f.
virtual RWvistream&
operator>>(int& i);
Redefined from class RWvistream. Get the next int from the input stream and store it in i.
virtual RWvistream&
operator>>(long& l);
Redefined from class RWvistream. Get the next long from the input stream and store it in l.
virtual RWvistream&
operator>>(short& s);
Redefined from class RWvistream. Get the next short from the input stream and store it in s.
virtual RWvistream&
operator>>(unsigned char& c);
Redefined from class RWvistream. Get the next unsigned char from the input stream and store it in c.
virtual RWvistream&
operator>>(unsigned short& s);
Redefined from class RWvistream. Get the next unsigned short from the input stream and store it in s.
virtual RWvistream&
operator>>(unsigned int& i);
Redefined from class RWvistream. Get the next unsigned int from the input stream and store it in i.
virtual RWvistream&
operator>>(unsigned long& l);
Redefined from class RWvistream. Get the next unsigned long from the input stream and store it in l.
operator void*();
Inherited via RWvistream from RWvios.

Public Member Functions

virtual int
get();
Redefined from class RWvistream. Get and return the next char from the input stream. Returns EOF if end of file is encountered.
virtual RWvistream&
get(char& c);
Redefined from class RWvistream. Get the next char and store it in c.
virtual RWvistream&
get(wchar_t& wc);
Redefined from class RWvistream. Get the next wide char and store it in wc.
virtual RWvistream&
get(unsigned char& c);
Redefined from class RWvistream. Get the next unsigned char and store it in c.
virtual RWvistream&
get(char* v, size_t N);
Redefined from class RWvistream. Get a vector of chars and store them in the array beginning at v. If the restore operation stops prematurely, because there are no more data available on the stream, because an exception is thrown, or for some other reason; get stores what has already been retrieved from the stream into v, and sets the failbit.
virtual RWvistream&
get(wchar_t* v, size_t N);
Redefined from class RWvistream. Get a vector of wide chars and store them in the array beginning at v. If the restore operation stops prematurely, because there are no more data available on the stream, because an exception is thrown, or for some other reason; get stores what has already been retrieved from the stream into v, and sets the failbit.
virtual RWvistream&
get(double* v, size_t N);
Redefined from class RWvistream. Get a vector of doubles and store them in the array beginning at v. If the restore operation stops prematurely, because there are no more data available on the stream, because an exception is thrown, or for some other reason; get stores what has already been retrieved from the stream into v, and sets the failbit.
virtual RWvistream&
get(float* v, size_t N);
Redefined from class RWvistream. Get a vector of floats and store them in the array beginning at v. If the restore operation stops prematurely, because there are no more data available on the stream, because an exception is thrown, or for some other reason; get stores what has already been retrieved from the stream into v, and sets the failbit.
virtual RWvistream&
get(int* v, size_t N);
Redefined from class RWvistream. Get a vector of ints and store them in the array beginning at v. If the restore operation stops prematurely, because there are no more data available on the stream, because an exception is thrown, or for some other reason; get stores what has already been retrieved from the stream into v, and sets the failbit.
virtual RWvistream&
get(long* v, size_t N);
Redefined from class RWvistream. Get a vector of longs and store them in the array beginning at v. If the restore operation stops prematurely, because there are no more data available on the stream, because an exception is thrown, or for some other reason; get stores what has already been retrieved from the stream into v, and sets the failbit.
virtual RWvistream&
get(short* v, size_t N);
Redefined from class RWvistream. Get a vector of shorts and store them in the array beginning at v. If the restore operation stops prematurely, because there are no more data available on the stream, because an exception is thrown, or for some other reason; get stores what has already been retrieved from the stream into v, and sets the failbit.
virtual RWvistream&
get(unsigned char* v, size_t N);
Redefined from class RWvistream. Get a vector of unsigned chars and store them in the array beginning at v. If the restore operation stops prematurely, because there are no more data available on the stream, because an exception is thrown, or for some other reason; get stores what has already been retrieved from the stream into v, and sets the failbit.
virtual RWvistream&
get(unsigned short* v, size_t N);
Redefined from class RWvistream. Get a vector of unsigned shorts and store them in the array beginning at v. If the restore operation stops prematurely, because there are no more data available on the stream, because an exception is thrown, or for some other reason; get stores what has already been retrieved from the stream into v, and sets the failbit.
virtual RWvistream&
get(unsigned int* v, size_t N);
Redefined from class RWvistream. Get a vector of unsigned ints and store them in the array beginning at v. If the restore operation stops prematurely, because there are no more data available on the stream, because an exception is thrown, or for some other reason; get stores what has already been retrieved from the stream into v, and sets the failbit.
virtual RWvistream&
get(unsigned long* v, size_t N);
Redefined from class RWvistream. Get a vector of unsigned longs and store them in the array beginning at v. If the restore operation stops prematurely, because there are no more data available on the stream, because an exception is thrown, or for some other reason; get stores what has already been retrieved from the stream into v, and sets the failbit.
virtual RWvistream&
getString(char* s, size_t N);
Redefined from class RWvistream. Restores a character string from the input stream and stores it in the array beginning at s. The function stops reading at the end of the string or after N-1 characters, whichever comes first. If N- 1 characters have been read and the Nth character is not the string terminator, then the failbit of the stream will be set. In either case, the string will be terminated with a null byte.
virtual RWvistream&
getString(wchar_t* ws, size_t N);
Redefined from class RWvistream. Restores a wide character string from the input stream and stores it in the array beginning at ws. The function stops reading at the end of the string or after N-1 characters, whichever comes first. If N-1 characters have been read and the Nth character is not the string terminator, then the failbit of the stream will be set. In either case, the string will be terminated with a null byte.
RWBitVec

RWBitVec

Synopsis

#include <rw/bitvec.h>
RWBitVec v;

Description

Class RWBitVec is a bitvector whose length can be changed at run time. Because this requires an extra level of indirection, this makes it slightly less efficient than classes RWGBitVec(size) or RWTBitVec<size>, whose lengths are fixed at compile time.

Persistence

Simple

Example


  #include <rw/bitvec.h>  
  #include <rw/rstream.h>  
  
  main(){  
     // Allocate a vector with 20 bits, set to TRUE:  
     RWBitVec av(20, TRUE);  
  
     av(2) = FALSE;     // Turn bit 2 off  
     av.clearBit(7);    // Turn bit 7 off  
     av.setBit(2);      // Turn bit 2 back on  
  
     for(int i=11; i<=14; i++) av(i) = FALSE;  
  
     cout << av << endl;    // Print the vector out  
  }  

Program output:


     [  
     1 1 1 1 1 1 1 0 1 1 1 0 0 0 0 1 1 1 1 1  
     ]  

Public Constructors

RWBitVec();
Construct a zero lengthed (null) vector.
RWBitVec(size_t N);
Construct a vector with N bits. The initial value of the bits is undefined.
RWBitVec(size_t N, RWBoolean initVal);
Construct a vector with N bits, each set to the Boolean value initVal.
RWBitVec(const RWByte* bp, size_t N);
Construct a vector with N bits, initialized to the data in the array of bytes pointed to by bp. This array must be at least long enough to contain N bits. The identifier RWByte is a typedef for an unsigned char.
RWBitVec(const RWBitVec& v);
Copy constructor. Uses value semantics -- the constructed vector will be a copy of v.
~RWBitVec();
The destructor. Releases any allocated memory.

Assignment Operators

RWBitVec&
operator=(const RWBitVec& v);
Assignment operator. Value semantics are used -- self will be a copy of v.
RWBitVec&
operator=(RWBoolean b);
Assignment operator. Sets every bit in self to the boolean value b.
RWBitVec&
operator&=(const RWBitVec& v);
RWBitVec&
operator^=(const RWBitVec& v);
RWBitVec&
operator|=(const RWBitVec& v);
Logical assignments. Set each element of self to the logical AND, XOR, or OR, respectively, of self and the corresponding bit in v. Self and v must have the same number of elements (i.e., be conformal) or an exception of type RWInternalErr will occur.

Indexing Operators

RWBitRef
operator[](size_t i);
Returns a reference to bit i of self. A helper class, RWBitRef, is used. The result can be used as an lvalue. The index i must be between 0 and the length of the vector less one. Bounds checking is performed. If the index is out of range, then an exception of type RWBoundsErr will occur.
RWBitRef
operator()(size_t i);
Returns a reference to bit i of self. A helper class, RWBitRef, is used. The result can be used as an lvalue. The index i must be between 0 and the length of the vector less one. Bounds checking is performed only if the preprocessor macro RWBOUNDS_CHECK has been defined before including the header file <rw/bitvec.h>. If so, and if the index is out of range, then an exception of type RWBoundsErr will occur.
RWBoolean
operator[](size_t i) const;
Returns the boolean value of bit i. The result cannot be used as an lvalue. The index i must be between 0 and the length of the vector less one. Bounds checking is performed. If the index is out of range, then an exception of type RWBoundsErr will occur.
RWBoolean
operator()(size_t i) const;
Returns the boolean value of bit i. The result cannot be used as an lvalue. The index i must be between 0 and the length of the vector less one. Bounds checking is performed only if the preprocessor macro RWBOUNDS_CHECK has been defined before including the header file <rw/bitvec.h>. If so, and if the index is out of range, then an exception of type RWBoundsErr will occur.

Logical Operators

RWBoolean
operator==(const RWBitVec& u) const;
Returns TRUE if self and v have the same length and if each bit of self is set to the same value as the corresponding bit in v. Otherwise, returns FALSE.
RWBoolean
operator!=(const RWBitVec& u) const;
Returns FALSE if self and v have the same length and if each bit of self is set to the same value as the corresponding bit in v. Otherwise, returns TRUE.
RWBoolean
operator==(RWBoolean b) const;
Returns TRUE if every bit of self is set to the boolean value b. Otherwise FALSE.
RWBoolean
operator!=(RWBoolean b) const;
Returns FALSE if every bit of self is set to the boolean value b. Otherwise TRUE.

Public Member Functions

void
clearBit(size_t i);
Clears (i.e., sets to FALSE) the bit with index i. The index i must be between 0 and the length of the vector less one. No bounds checking is performed. The following are equivalent, although clearBit(size_t) is slightly smaller and faster than using operator()(size_t):
   a(i) = FALSE;
   a.clearBit(i);
const RWByte*
data() const;
Returns a const pointer to the raw data of self. Should be used with care.
size_t
firstFalse() const;
Returns the index of the first FALSE bit in self. Returns RW_NPOS if there is no FALSE bit.
size_t
firstTrue() const;
Returns the index of the first TRUE bit in self. Returns RW_NPOS if there is no TRUE bit.
unsigned
hash() const;
Returns a value suitable for hashing.
RWBoolean
isEqual(const RWBitVec& v) const;
Returns TRUE if self and v have the same length and if each bit of self is set to the same value as the corresponding bit in v. Otherwise, returns FALSE.
size_t
length() const;
Returns the number of bits in the vector.
ostream&
printOn(ostream& s) const;
Print the vector v on the output stream s. See the example above for a sample of the format.
void
resize(size_t N);
Resizes the vector to have length N. If this results in a lengthening of the vector, the additional bits will be set to FALSE.
istream&
scanFrom(istream&);
Read the bit vector from the input stream s. The vector will dynamically be resized as necessary. The vector should be in the same format printed by member function printOn(ostream&).
void
setBit(size_t i);
Sets (i.e., sets to TRUE) the bit with index i. The index i must be between 0 and size-1. No bounds checking is performed. The following are equivalent, although setBit(size_t) is slightly smaller and faster than using operator()(size_t):
   a(i) = TRUE;
   a.setBit(i);
RWBoolean
testBit(size_t i) const;
Tests the bit with index i. The index i must be between 0 and size-1. No bounds checking is performed. The following are equivalent, although testBit(size_t) is slightly smaller and faster than using
  operator()(size_t):
   if( a(i) )              doSomething();
   if( a.testBit(i) )      doSomething();

Related Global Functions

RWBitVec
operator!(const RWBitVec& v);
Unary operator that returns the logical negation of vector v.
RWBitVec
operator&(const RWBitVec&,const RWBitVec&);
RWBitVec
operator^(const RWBitVec&,const RWBitVec&);
RWBitVec
operator|(const RWBitVec&,const RWBitVec&);
Returns a vector that is the logical AND, XOR, or OR of the vectors v1 and v2. The two vectors must have the same length or an exception of type RWInternalErr will occur.
ostream&
operator<<(ostream& s, const RWBitVec& v);
Calls v.printOn(s).
istream&
operator>>(istream& s, RWBitVec& v);
Calls v.scanFrom(s).
RWvostream&
operator<<(RWvostream&, const RWBitVec& vec);
RWFile&
operator<<(RWFile&,     const RWBitVec& vec);
Saves the RWBitVec vec to a virtual stream or RWFile, respectively.
RWvistream&
operator>>(RWvistream&, RWBitVec& vec);
RWFile&
operator>>(RWFile&,     RWBitVec& vec);
Restores an RWBitVec into vec from a virtual stream or RWFile, respectively, replacing the previous contents of vec.
size_t
sum(const RWBitVec& v);
Returns the total number of bits set in the vector v.
RWbostream

RWbostream

. RWvostream . RWios . RWvios
RWbostream
. ios

Synopsis

#include <rw/bstream.h>
// Construct an RWbostream, using cout's streambuf:
RWbostream bstr(cout);

Description

Class RWbostream specializes the abstract base class RWvostream to store variables in binary format. The results can be restored by using its counterpart RWbistream.
You can think of it as a binary veneer over an associated streambuf. Because the RWbostream retains no information about the state of its associated streambuf, its use can be freely exchanged with other users of the streambuf (such as ostream or ofstream).
Note that variables should not be separated with white space. Such white space would be interpreted literally and would have to be read back in as a character string.
RWbostream can be interrogated as to the stream state using member functions good(), bad(), eof(), etc.

Persistence

None

Example

See RWbistream for an example of how the file "data.dat" might be read back in.

  #include <rw/bstream.h>  
  #include <fstream.h>  
  
  main(){  
    ofstream fstr("data.dat");   // Open an output file  
    RWbostream bstr(fstr);       // Construct an RWbostream from it  
  
    int i = 5;  
    float f = 22.1;  
    double d = -0.05;  
  
    bstr << i;             // Store an int in binary  
    bstr << f << d;        // Store a float & double  
  }  

Public Constructors

RWbostream(streambuf* s);
Construct an RWbostream from the streambuf s. For DOS, the streambuf must have been opened in binary mode.
RWbostream(ostream& str);
Construct an RWbostream from the streambuf associated with the output stream str. For DOS, the streambuf must have been opened in binary mode. This can be done by specifying ios::binary as part of the second argument to the constructor for an ofstream. Using the example above, the line to create the ofstream would read, ofstream fstr("data.dat", ios::out | ios::binary); where the "|" is the binary OR operator.

Public Destructor

virtual ~RWvostream();
This virtual destructor allows specializing classes to deallocate any resources that they may have allocated.

Public Operators

virtual RWvostream&
operator<<(const char* s);
Redefined from class RWvostream. Store the character string starting at s to the output stream in binary. The character string is expected to be null terminated.
virtual RWvostream&
operator<<(const wchar_t* ws);
Redefined from class RWvostream. Store the wide character string starting at ws to the output stream in binary. The wide character string is expected to be null terminated.
virtual RWvostream&
operator<<(char c);
Redefined from class RWvostream. Store the char c to the output stream in binary.
virtual RWvostream&
operator<<(wchar_t wc);
Redefined from class RWvostream. Store the wide char wc to the output stream in binary.
virtual RWvostream&
operator<<(unsigned char c);
Redefined from class RWvostream. Store the unsigned char c to the output stream in binary.
virtual RWvostream&
operator<<(double d);
Redefined from class RWvostream. Store the double d to the output stream in binary.
virtual RWvostream&
operator<<(float f);
Redefined from class RWvostream. Store the float f to the output stream in binary.
virtual RWvostream&
operator<<(int i);
Redefined from class RWvostream. Store the int i to the output stream in binary.
virtual RWvostream&
operator<<(unsigned int i);
Redefined from class RWvostream. Store the unsigned int i to the output stream in binary.
virtual RWvostream&
operator<<(long l);
Redefined from class RWvostream. Store the long l to the output stream in binary.
virtual RWvostream&
operator<<(unsigned long l);
Redefined from class RWvostream. Store the unsigned long l to the output stream in binary.
virtual RWvostream&
operator<<(short s);
Redefined from class RWvostream. Store the short s to the output stream in binary.
virtual RWvostream&
operator<<(unsigned short s);
Redefined from class RWvostream. Store the unsigned short s to the output stream in binary.
operator void*();
Inherited via RWvostream from RWvios.

Public Member Functions

virtual RWvostream&
flush();
Send the contents of the stream buffer to output immediately.
virtual RWvostream&
put(char c);
Redefined from class RWvostream. Store the char c to the output stream.
virtual RWvostream&
put(wchar_t wc);
Redefined from class RWvostream. Store the wide character wc to the output stream.
virtual RWvostream&
put(unsigned char c);
Redefined from class RWvostream. Store the unsigned char c to the output stream.
virtual RWvostream&
put(const char* p, size_t N);
Redefined from class RWvostream. Store the vector of chars starting at p to the output stream in binary.
virtual RWvostream&
put(const wchar_t* p, size_t N);
Redefined from class RWvostream. Store the vector of wide chars starting at p to the output stream in binary.
virtual RWvostream&
put(const unsigned char* p, size_t N);
Redefined from class RWvostream. Store the vector of unsigned chars starting at p to the output stream in binary.
virtual RWvostream&
put(const short* p, size_t N);
Redefined from class RWvostream. Store the vector of shorts starting at p to the output stream in binary.
virtual RWvostream&
put(const unsigned short* p, size_t N);
Redefined from class RWvostream. Store the vector of unsigned shorts starting at p to the output stream in binary.
virtual RWvostream&
put(const int* p, size_t N);
Redefined from class RWvostream. Store the vector of ints starting at p to the output stream in binary.
virtual RWvostream&
put(const unsigned int* p, size_t N);
Redefined from class RWvostream. Store the vector of unsigned ints starting at p to the output stream in binary.
virtual RWvostream&
put(const long* p, size_t N);
Redefined from class RWvostream. Store the vector of longs starting at p to the output stream in binary.
virtual RWvostream&
put(const unsigned long* p, size_t N);
Redefined from class RWvostream. Store the vector of unsigned longs starting at p to the output stream in binary.
virtual RWvostream&
put(const float* p, size_t N);
Redefined from class RWvostream. Store the vector of floats starting at p to the output stream in binary.
virtual RWvostream&
put(const double* p, size_t N);
Redefined from class RWvostream. Store the vector of doubles starting at p to the output stream in binary.
virtual RWvostream&
putString(const char* p, size_t N);
Redefined from class RWvostream. Data is formatted as a string containing N characters.
virtual RWvostream&
putString(const char*s, size_t N);
Store the character string, including embedded nulls, starting at s to the output string.
RWBTree

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

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

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.
V6StyleInitialize a new tree using V6.X style trees. This is the default.
V5StyleInitialize 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.
autoCreateLook 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.
createForces 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:
fThe file in which the B-tree is to be managed. This is the only required parameter.
nbufThe maximum number of nodes that can be cached in memory.
omodeDetermines whether to force the creation of a new tree or whether to attempt to open an existing tree for update (the default).
keylenThe length of a key in bytes. Ignored when opening an existing tree.
ignoreNullControls 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.
startWhere 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.
smodeSets 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.
halfOrderOne half the order of the B-tree (that is, one half the number of entries in a node). Ignored when opening an existing tree.
minFillThe 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

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

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

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

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.,
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 unsigned short). 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 1 not.
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);

1. See the section in the User's Guide entitled "RWString ID" for more information on how to make a non-virtual function act like a virtual function.
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

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

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

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

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 RWCString s.
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

RWCollectableTime

. RWCollectable
RWCollectableTime
. RWTime

Synopsis

typedef RWCollectableTime ;  // 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

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

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. 1 Any character that is not a special character (to be defined) matches itself.

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

  1. 3 The "special characters" are:

          +     *     ?     .     [     ]     ^     $
  1. 4 The period (.) matches any character except the newline. E.g., ".umpty" matches either "Humpty" or "Dumpty."

  1. 5 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. 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.

  1. 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.

  1. 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.

  1. 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. 1 If the caret (^) is at the beginning of the RE, then the matched string must be at the beginning of a line.

  1. 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:
\bbackspace
\e ESC (escape)
\fformfeed
\nnewline
\rcarriage return
\ttab
\xdddthe literal hex number 0xdd
\dddthe literal octal number ddd
\^CControl 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"  
  }  

Public Constructors

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:
statValMeaning
RWCRegexp::OKNo errors
RWCRegexp::ILLEGALPattern was illegal
RWCRegexp::TOOLONG1 Pattern exceeded maximum length
1. To change the amount of space allocated for a pattern you may edit file regexp.cpp to change the value of RWCRegexp::maxval_, then recompile and insert the changed object into the appropriate library.
RWCRExpr

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:

+ * ?  . [  ] ^ $ ( ) { } | \
  1. The period (.) matches any character. 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. 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.

  2. 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.

  3. 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.

  4. 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.

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

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

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

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

  3. 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.

  4. 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.

Public Destructor

~RWCRExpr();
Destructor. Releases any allocated memory.

Assignment Operators

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().

Public Member Functions

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:
statusTypeMeaning
RWCRExpr::OKNo errors
RWCRExpr::NOT_SUPPORTEDPOSIX.2 feature not yet supported.
RWCRExpr::NO_MATCHTried to find a match but failed
RWCRExpr::BAD_PATTERNPattern was illegal
RWCRExpr::BAD_COLLATING_ELEMENTInvalid collating element referenced
RWCRExpr::BAD_CHAR_CLASS_TYPEInvalid character class type referenced
RWCRExpr::TRAILING_BACKSLASHTrailing \ in pattern
RWCRExpr::UNMATCHED_BRACKET[] imbalance
RWCRExpr::UNMATCHED_PARENTHESIS() imbalance
RWCRExpr::UNMATCHED_BRACE{} imbalance
RWCRExpr::BAD_BRACEContent of {} invalid.
statusTypeMeaning
RWCRExpr::BAD_CHAR_RANGEInvalid endpoint in [a-z] expression
RWCRExpr::OUT_OF_MEMORYOut of memory
RWCRExpr::BAD_REPEAT?,* or + not preceded by valid regular expression
RWCString

RWCString

Synopsis

#include <rw/cstring.h>
RWCString a;

Description

Class RWCString offers very powerful and convenient facilities for manipulating strings that are just as efficient as the familiar standard C <string.h> functions.
Although the class is primarily intended to be used to handle single-byte character sets (SBCS; such as ASCII or ISO Latin-1), with care it can be used to handle multibyte character sets (MBCS). There are two things that must be kept in mind when working with MBCS:
  • Because characters can be more than one byte long, the number of bytes in a string can, in general, be greater than the number of characters in the string. Use function RWCString::length() to get the number of bytes in a string, function RWCString::mbLength() to get the number of characters. Note that the latter is much slower because it must determine the number of bytes in every character. Hence, if the string is known to be nothing but SBCS, then RWCString::length() is much to be preferred.
  • One or more bytes of a multibyte character can be zero. Hence, MBCS cannot be counted on being null terminated. In practice, it is a rare MBCS that uses embedded nulls. Nevertheless, you should be aware of this and program defensively. In any case, class RWCString can handle embedded nulls.
Parameters of type "const char*" must not be passed a value of zero. This is detected in the debug version of the library.
The class is implemented using a technique called copy on write. With this technique, the copy constructor and assignment operators still reference the old object and hence are very fast. An actual copy is made only when a "write" is performed, that is if the object is about to be changed. The net result is excellent performance, but with easy-to-understand copy semantics.
A separate class RWCSubString supports substring extraction and modification operations.

Persistence

Simple

Example


  #include <rw/re.h>  
  #include <rw/rstream.h>  
  
  main(){  
    RWCString a("There is no joy in Beantown.");  
  
    cout << a << endl << "becomes...." << endl;  
  
    RWCRExpr re("[A-Z][a-z]*town");  // Any capitalized "town"  
    a.replace(re, "Redmond");  
    cout << a << endl;  
  }  

Program output:


  There is no joy in Redmond.  

Enumerations

enum RWCString::caseCompare { exact, ignoreCase }
Used to specify whether comparisons, searches, and hashing functions should use case sensitive (exact) or case-insensitive (ignoreCase) semantics.
enum RWCString::scopeType { one, all }
Used to specify whether regular expression replace replaces the first one substring matched by the regular expression or replaces all substrings matched by the regular expression.

Public Constructors

RWCString();
Creates a string of length zero (the null string).
RWCString(const char* cs);
Conversion from the null-terminated character string cs. The created string will copy the data pointed to by cs, up to the first terminating null. This function is incompatible with cs strings with embedded nulls. This function may be incompatible with cs MBCS strings.
RWCString(const char* cs, size_t N);
Constructs a string from the character string cs. The created string will copy the data pointed to by cs. Exactly N bytes are copied, including any embedded nulls. Hence, the buffer pointed to by cs must be at least N bytes long.
RWCString(RWSize_T ic);
Creates a string of length zero (the null string). The string's capacity (that is, the size it can grow to without resizing) is given by the parameter ic. We recommend creating an RWSize_T value from a numerical constant to pass into this constructor. While RWSize_T knows how to convert size_t's to itself, conforming compilers will chose the conversion to char instead.
RWCString(const RWCString& str);
Copy constructor. The created string will copy str's data.
RWCString(const RWCSubString& ss);
Conversion from sub-string. The created string will copy the substring represented by ss.
RWCString(char c);
Constructs a string containing the single character c.
RWCString(char c, size_t N);
Constructs a string containing the character c repeated N times.

Type Conversion

operator
const char*() const;
Access to the RWCString's data as a null terminated string. This data is owned by the RWCString and may not be deleted or changed. If the RWCString object itself changes or goes out of scope, the pointer value previously returned may (will!) become invalid. While the string is null-terminated, note that its length is still given by the member function length(). That is, it may contain embedded nulls.

Assignment Operators

RWCString&
operator=(const char* cs);
Assignment operator. Copies the null-terminated character string pointed to by cs into self. Returns a reference to self. This function is incompatible with cs strings with embedded nulls. This function may be incompatible with cs MBCS strings.
RWCString& operator=(const RWCString& str);
Assignment operator. The string will copy str's data. Returns a reference to self.
RWCString&
operator+=(const char* cs);
Append the null-terminated character string pointed to by cs to self. Returns a reference to self. This function is incompatible with cs strings with embedded nulls. This function may be incompatible with cs MBCS strings.
RWCString&
operator+=(const RWCString& str);
Append the string str to self. Returns a reference to self.

Indexing Operators

char&
operator[](size_t i);
char
operator[](size_t i) const;
Return the ith byte. The first variant can be used as an lvalue. The index i must be between 0 and the length of the string less one. Bounds checking is performed -- if the index is out of range then an exceptionof type RWBoundsErr will occur.
char&
operator()(size_t i);
char
operator()(size_t i) const;
Return the ith byte. The first variant can be used as an lvalue. The index i must be between 0 and the length of the string less one. Bounds checking is performed if the pre-processor macro RWBOUNDS_CHECK has been defined before including <rw/cstring.h>. In this case, if the index is out of range, then an exception of type RWBoundsErr will occur.
RWCSubString
operator()(size_t start, size_t len);
const RWCSubString
operator()(size_t start, size_t len) const;
Substring operator. Returns an RWCSubString of self with length len, starting at index start. The first variant can be used as an lvalue. The sum of start plus len must be less than or equal to the string length. If the library was built using the RWDEBUG flag, and start and len are out of range, then an exception of type RWBoundsErr will occur.
RWCSubString
operator()(const RWCRExpr& re, size_t start=0);
const RWCSubString
operator()(const RWCRExpr& re, size_t start=0) const;
RWCSubString
operator()(const RWCRegexp& re, size_t start=0);
const RWCSubString
operator()(const RWCRegexp& re, size_t start=0) const;
Returns the first substring starting after index start that matches the regular expression re. If there is no such substring, then the null substring is returned. The first variant can be used as an lvalue.
Note that if you wish to use operator()(const RWCRExpr&...) you must instead use match(const RWCRExpr&...) described below. The reason for this is that we are presently retaining RWCRegexp but operator(const RWCRExpr&...) and operator(const RWCRegexp) are ambiguous in the case of RWCString::operator("string"). In addition, operator(const char *) and operator(size_t) are ambiguous in the case of RWCString::operator(0). This function maybe incompatible with strings with embedded nulls. This function is incompatible with MBCS strings.

Public Member Functions

RWCString&
append(const char* cs);
Append a copy of the null-terminated character string pointed to by cs to self. Returns a reference to self. This function is incompatible with cs strings with embedded nulls. This function may be incompatible with cs MBCS strings.
RWCString&
append(const char* cs, size_t N);
Append a copy of the character string cs to self. Exactly N bytes are copied, including any embedded nulls. Hence, the buffer pointed to by cs must be at least N bytes long. Returns a reference to self.
RWCString&
append(char c, size_t N);
Append N copies of the character c to self. Returns a reference to self.
RWCString&
append(const RWCString& cstr);
Append a copy of the string cstr to self. Returns a reference to self.
RWCString&
append(const RWCString& cstr, size_t N);
Append the first N bytes or the length of cstr (whichever is less) of cstr to self. Returns a reference to self.
size_t
binaryStoreSize() const;
Returns the number of bytes necessary to store the object using the global function:
RWFile& operator<<(RWFile&, const RWCString&);
size_t
capacity() const;
Return the current capacity of self. This is the number of bytes the string can hold without resizing.
size_t
capacity(size_t capac);
Hint to the implementation to change the capacity of self to capac. Returns the actual capacity.
int
collate(const char* str) const;
int
collate(const RWCString& str) const;
Returns an int less then, greater than, or equal to zero, according to the result of calling the standard C library function ::strcoll() on self and the argument str. This supports locale-dependent collation. Provided only on platforms that provide ::strcoll(). This function is incompatible with strings with embedded nulls.
int
compareTo(const char* str, caseCompare = RWCString::exact) const;
int
compareTo(const RWCString& str,
          caseCompare = RWCString::exact) const;
Returns an int less than, greater than, or equal to zero, according to the result of calling the standard C library function memcmp() on self and the argument str. Case sensitivity is according to the caseCompare argument, and may be RWCString::exact or RWCString::ignoreCase. If caseCompare is RWCString::exact, then this function works for all string types. Otherwise, this function is incompatible with MBCS strings. This function is incompatible with const char* strings with embedded nulls. This function may be incompatible with const char* MBCS strings.
RWBoolean
contains(const char* str, caseCompare = RWCString::exact)
         const;
RWBoolean
contains(const RWCString& cs,
         caseCompare = RWCString::exact) const;
Pattern matching. Returns TRUE if str occurs in self. Case sensitivity is according to the caseCompare argument, and may be RWCString::exact or RWCString::ignoreCase. If caseCompare is RWCString::exact, then this function works for all string types. Otherwise, this function is incompatible with MBCS strings. This function is incompatible with const char* strings with embedded nulls. This function may be incompatible with const char* MBCS strings.
const char*
data() const;
Access to the RWCString's data as a null terminated string. This datum is owned by the RWCString and may not be deleted or changed. If the RWCString object itself changes or goes out of scope, the pointer value previously returned will become invalid. While the string is null terminated, note that its length is still given by the member function length(). That is, it may contain embedded nulls.
size_t
first(char c) const;
Returns the index of the first occurence of the character c in self. Returns RW_NPOS if there is no such character or if there is an embedded null prior to finding c. This function is incompatible with strings with embedded nulls. This function is incompatible with MBCS strings.
size_t
first(char c, size_t) const;
Returns the index of the first occurence of the character c in self. Continues to search past embedded nulls. Returns RW_NPOS if there is no such character. This function is incompatible with MBCS strings.
size_t
first(const char* str) const;
Returns the index of the first occurence in self of any character in str. Returns RW_NPOS if there is no match or if there is an embedded null prior to finding any character from str. This function is incompatible with strings with embedded nulls. This function may be incompatible with MBCS strings.
size_t
first(const char* str, size_t N) const;
Returns the index of the first occurence in self of any character in str. Exactly N bytes in str are checked including any embedded nulls so str must point to a buffer containing at least N bytes. Returns RW_NPOS if there is no match.
unsigned
hash(caseCompare = RWCString::exact) const;
Returns a suitable hash value. If caseCompare is RWCString::ignoreCase then this function will be incompatible with MBCS strings.
size_t
index(const char* pat,size_t i=0,
      caseCompare = RWCString::exact) const;
size_t
index(const RWCString& pat,size_t i=0,
      caseCompare = RWCString::exact) const;
Pattern matching. Starting with index i, searches for the first occurrence of pat in self and returns the index of the start of the match. Returns RW_NPOS if there is no such pattern. Case sensitivity is according to the caseCompare argument; it defaults to RWCString::exact. If caseCompare is RWCString::exact, then this function works for all string types. Otherwise, this function is incompatible with MBCS strings.
size_t
index(const char* pat, size_t patlen,size_t i,
      caseCompare cmp) const;
size_t
index(const RWCString& pat, size_t patlen,size_t i,
      caseCompare cmp) const;
Pattern matching. Starting with index i, searches for the first occurrence of the first patlen bytes from pat in self and returns the index of the start of the match. Returns RW_NPOS if there is no such pattern. Case sensitivity is according to the caseCompare argument. If caseCompare is RWCString::exact, then this function works for all string types. Otherwise, this function is incompatible with MBCS strings.
size_t
index(const RWCRExpr& re, size_t i=0) const;
size_t
index(const RWCRegexp& re, size_t i=0) const;
Regular expression matching. Returns the index greater than or equal to i of the start of the first pattern that matches the regular expression re. Returns RW_NPOS if there is no such pattern. This function is incompatible with MBCS strings.
size_t
index(const RWCRExpr& re,size_t* ext,size_t i=0) const;
size_t
index(const RWCRegexp& re,size_t* ext,size_t i=0) const;
Regular expression matching. Returns the index greater than or equal to i of the start of the first pattern that matches the regular expression re. Returns RW_NPOS if there is no such pattern. The length of the matching pattern is returned in the variable pointed to by ext. This function is incompatible with strings with embedded nulls. This function may be incompatible with MBCS strings.
RWCString&
insert(size_t pos, const char* cs);
Insert a copy of the null-terminated string cs into self at byte position pos, thus expanding the string. Returns a reference to self. This function is incompatible with cs strings with embedded nulls. This function may be incompatible with cs MBCS strings.
RWCString&
insert(size_t pos, const char* cs, size_t N);
Insert a copy of the first N bytes of cs into self at byte position pos, thus expanding the string. Exactly N bytes are copied, including any embedded nulls. Hence, the buffer pointed to by cs must be at least N bytes long. Returns a reference to self.
RWCString&
insert(size_t pos, const RWCString& str);
Insert a copy of the string str into self at byte position pos. Returns a reference to self.
RWCString&
insert(size_t pos, const RWCString& str, size_t N);
Insert a copy of the first N bytes or the length of str (whichever is less) of str into self at byte position pos. Returns a reference to self.
RWBoolean
isAscii() const;
Returns TRUE if self contains no bytes with the high bit set.
RWBoolean
isNull() const;
Returns TRUE if this is a zero lengthed string (i.e., the null string).
size_t
last(char c) const;
Returns the index of the last occurrence in the string of the character c. Returns RW_NPOS if there is no such character or if there is an embedded null to the right of c in self. This function is incompatible with strings with embedded nulls. This function may be incompatible with MBCS strings.
size_t
last(char c, size_t N) const;
Returns the index of the last occurrence in the string of the character c. Continues to search past embedded nulls. Returns RW_NPOS if there is no such character. This function is incompatible with MBCS strings.
size_t
length() const;
Return the number of bytes in self. Note that if self contains multibyte characters, then this will not be the number of characters.
RWCSubString
match(const RWCRExpr& re, size_t start=0);
const RWCSubString
match(const RWCRExpr& re, size_t start=0) const;
Returns the first substring starting after index start that matches the regular expression re. If there is no such substring, then the null substring is returned. The first variant can be used as an lvalue. Note that this is used in place of operator()(const RWCRegexp&...) if you want to use extended regular expressions.
size_t
mbLength() const;
Return the number of multibyte characters in self, according to the Standard C function ::mblen(). Returns RW_NPOS if a bad character is encountered. Note that, in general, mbLength() . length(). Provided only on platforms that provide ::mblen().
RWCString&
prepend(const char* cs);
Prepend a copy of the null-terminated character string pointed to by cs to self. Returns a reference to self. This function is incompatible with cs strings with embedded nulls. This function may be incompatible with cs MBCS strings.
RWCString&
prepend(const char* cs, size_t N);
Prepend a copy of the character string cs to self. Exactly N bytes are copied, including any embedded nulls. Hence, the buffer pointed to by cs must be at least N bytes long. Returns a reference to self.
RWCString&
prepend(char c, size_t N);
Prepend N copies of character c to self. Returns a reference to self.
RWCString&
prepend(const RWCString& str);
Prepends a copy of the string str to self. Returns a reference to self.
RWCString&
prepend(const RWCString& cstr, size_t N);
Prepend the first N bytes or the length of cstr (whichever is less) of cstr to self. Returns a reference to self.
istream&
readFile(istream& s);
Reads characters from the input stream s, replacing the previous contents of self, until EOF is reached. Null characters are treated the same as other characters.
istream&
readLine(istream& s, RWBoolean skipWhite = TRUE);
Reads characters from the input stream s, replacing the previous contents of self, until a newline (or an EOF) is encountered. The newline is removed from the input stream but is not stored. Null characters are treated the same as other characters. If the skipWhite argument is TRUE, then whitespace is skipped (using the iostream library manipulator ws) before saving characters.
istream&
readString(istream& s);
Reads characters from the input stream s, replacing the previous contents of self, until an EOF or null terminator is encountered. If the number of bytes remaining in the stream is large, you should resize the RWCString to approximately the number of bytes to be read prior to using this method. See "Implementation Details" in the User's Guide for more information. This function is incompatible with strings with embedded nulls. This function may be incompatible with MBCS strings.
istream&
readToDelim(istream& s, char delim='\n');
Reads characters from the input stream s, replacing the previous contents of self, until an EOF or the delimiting character delim is encountered. The delimiter is removed from the input stream but is not stored. Null characters are treated the same as other characters. If delim is '\0' then this function is incompatible with strings with embedded nulls. If delim is '\0' then this function may be incompatible with MBCS strings.
istream&
readToken(istream& s);
Whitespace is skipped before saving characters. Characters are then read from the input stream s, replacing previous contents of self, until trailing whitespace or an EOF is encountered. The whitespace is left on the input stream. Null characters are treated the same as other characters. Whitespace is identified by the standard C library function isspace(). This function is incompatible with MBCS strings.
RWCString&
remove(size_t pos);
Removes the bytes from the byte position pos, which must be no greater than length(), to the end of string. Returns a reference to self.
RWCString&
remove(size_t pos, size_t N);
Removes N bytes or to the end of string (whichever comes first) starting at the byte position pos, which must be no greater than length(). Returns a reference to self.
RWCString&
replace(size_t pos, size_t N, const char* cs);
Replaces N bytes or to the end of string (whichever comes first) starting at byte position pos, which must be no greater than length(), with a copy of the null-terminated string cs. Returns a reference to self. This function is incompatible with cs strings with embedded nulls. This function may be incompatible with cs MBCS strings.
RWCString&
replace(size_t pos, size_t N1,const char* cs, size_t N2);
Replaces N1 bytes or to the end of string (whichever comes first) starting at byte position pos, which must be no greater than length(), with a copy of the string cs. Exactly N2 bytes are copied, including any embedded nulls. Hence, the buffer pointed to by cs must be at least N2 bytes long. Returns a reference to self.
RWCString&
replace(size_t pos, size_t N, const RWCString& str);
Replaces N bytes or to the end of string (whichever comes first) starting at byte position pos, which must be no greater than length(), with a copy of the string str. Returns a reference to self.
RWCString&
replace(size_t pos, size_t N1,const RWCString& str, size_t N2);
Replaces N1 bytes or to the end of string (whichever comes first) starting at position pos, which must be no greater than length(), with a copy of the first N2 bytes, or the length of str (whichever is less), from str. Returns a reference to self.
replace(const RWCRExpr& pattern, const char* replacement,
        scopeType scope=one);
replace(const RWCRExpr& pattern,
        const RWCString& replacement,scopeType scope=one);
Replaces substring matched by pattern with replacement string. pattern
is the new extended regular expression. scope is one of {one, all} and controls whether all matches of pattern are replaced with replacement or just the first one match is replaced. replacement is the replacement pattern for the string. Here's an example:
 RWCString s("hahahohoheehee");
 s.replace(RWCRExpr("(ho)+","HAR"); // s == "hahaHARheehee"
This function is incompatible with const char* replacement strings with embedded nulls. This function may be incompatible with const char* replacement MBCS strings.
void
resize(size_t n);
Changes the length of self to n bytes, adding blanks or truncating as necessary.
RWCSubString
strip(stripType s = RWCString::trailing, char c = ' ');
const RWCSubString
strip(stripType s = RWCString::trailing, char c = ' ')
const;
Returns a substring of self where the character c has been stripped off the beginning, end, or both ends of the string. The first variant can be used as an lvalue. The enum stripType can take values:
stripTypeMeaning
leadingRemove characters at beginning
trailingRemove characters at end
bothRemove characters at both ends
RWCSubString
subString(const char* cs, size_t start=0,
          caseCompare = RWCString::exact);
const RWCSubString
subString(const char* cs, size_t start=0,
          caseCompare = RWCString::exact) const;
Returns a substring representing the first occurence of the null-terminated string pointed to by "cs". The first variant can be used as an lvalue. Case sensitivity is according to the caseCompare argument; it defaults to RWCString::exact. If caseCompare is RWCString::ignoreCase then this function is incompatible with MBCS strings. This function is incompatible with cs strings with embedded nulls. This function may be incompatible with cs MBCS strings.
void
toLower();
Changes all upper-case letters in self to lower-case, using the standard C library facilities declared in <ctype.h>. This function is incompatible with MBCS strings.
void
toUpper();
Changes all lower-case letters in self to upper-case, using the standard C library facilities declared in <ctype.h>. This function is incompatible with MBCS strings.

Static Public Member Functions

static unsigned
hash(const RWCString& str);
Returns the hash value of str as returned by
  str.hash(RWCString::exact).
static size_t
initialCapacity(size_t ic = 15);
Sets the minimum initial capacity of an RWCString, and returns the old value. The initial setting is 15 bytes. Larger values will use more memory, but result in fewer resizes when concatenating or reading strings. Smaller values will waste less memory, but result in more resizes.
static size_t
maxWaste(size_t mw = 15);
Sets the maximum amount of unused space allowed in a string should it shrink, and returns the old value. The initial setting is 15 bytes. If more than mw bytes are wasted, then excess space will be reclaimed.
static size_t
resizeIncrement(size_t ri = 16);
Sets the resize increment when more memory is needed to grow a string. Returns the old value. The initial setting is 16 bytes.

Related Global Operators

RWBoolean
operator==(const RWCString&, const char*     );
RWBoolean
operator==(const char*,      const RWCString&);
RWBoolean
operator==(const RWCString&, const RWCString&);
RWBoolean
operator!=(const RWCString&, const char*     );
RWBoolean
operator!=(const char*,      const RWCString&);
RWBoolean
operator!=(const RWCString&, const RWCString&);
Logical equality and inequality. Case sensitivity is exact. This function is incompatible with const char* strings with embedded nulls. This function may be incompatible with const char* MBCS strings.
RWBoolean
operator< (const RWCString&, const char*     );
RWBoolean
operator< (const char*,      const RWCString&);
RWBoolean
operator< (const RWCString&, const RWCString&);
RWBoolean
operator> (const RWCString&, const char*     );
RWBoolean
operator> (const char*,      const RWCString&);
RWBoolean
operator> (const RWCString&, const RWCString&);
RWBoolean
operator<=(const RWCString&, const char*     );
RWBoolean
operator<=(const char*,      const RWCString&);
RWBoolean
operator<=(const RWCString&, const RWCString&);
RWBoolean
operator>=(const RWCString&, const char*     );
RWBoolean
operator>=(const char*,      const RWCString&);
RWBoolean
operator>=(const RWCString&, const RWCString&);
Comparisons are done lexicographically, byte by byte. Case sensitivity is exact. Use member collate() or strxfrm() for locale sensitivity. This function is incompatible with const char* strings with embedded nulls. This function may be incompatible with const char* MBCS strings.
RWCString
operator+(const RWCString&, const RWCString&);
RWCString
operator+(const char*,      const RWCString&);
RWCString
operator+(const RWCString&, const char*     );
Concatenation operators. This function is incompatible with const char* strings with embedded nulls. This function may be incompatible with const char* MBCS strings.
ostream&
operator<<(ostream& s, const RWCString&);
Output an RWCString on ostream s.
istream&
operator>>(istream& s, RWCString& str);
Calls str.readToken(s). That is, a token is read from the input stream s. This function is incompatible with MBCS strings.
RWvostream&
operator<<(RWvostream&, const RWCString& str);
RWFile&
operator<<(RWFile&,     const RWCString& str);
Saves string str to a virtual stream or RWFile, respectively.
RWvistream&
operator>>(RWvistream&, RWCString& str);
RWFile&
operator>>(RWFile&,     RWCString& str);
Restores a string into str from a virtual stream or RWFile, respectively, replacing the previous contents of str.

Related Global Functions

RWCString
strXForm(const RWCString&);
Returns the result of applying ::strxfrm() to the argument string, to allow quicker collation than RWCString::collate(). Provided only on platforms that provide ::strxfrm(). This function is incompatible with strings with embedded nulls.
RWCString
toLower(const RWCString& str);
Returns a version of str where all upper-case characters have been replaced with lower-case characters. Uses the standard C library function tolower(). This function is incompatible with MBCS strings.
RWCString
toUpper(const RWCString& str);
Returns a version of str where all lower-case characters have been replaced with upper-case characters. Uses the standard C library function toupper(). This function is incompatible with MBCS strings.
RWCSubString

RWCSubString

Synopsis

#include <rw/cstring.h>
RWCString s("test string");
s(6,3);     // "tri"

Description

The class RWCSubString allows some subsection of an RWCString to be addressed by defining a starting position and an extent. For example the 7th through the 11th elements, inclusive, would have a starting position of 7 and an extent of 5. The specification of a starting position and extent can also be done in your behalf by such functions as RWCString::strip() or the overloaded function call operator taking a regular expression as an argument. There are no public constructors -- RWCSubStrings are constructed by various functions of the RWCString class and then destroyed immediately.
A zero length substring is one with a defined starting position and an extent of zero. It can be thought of as starting just before the indicated character, but not including it. It can be used as an lvalue. A null substring is also legal and is frequently used to indicate that a requested substring, perhaps through a search, does not exist. A null substring can be detected with member function isNull(). However, it cannot be used as an lvalue.

Persistence

None

Example


  #include <rw/cstring.h>  
  #include <rw/rstream.h>  
  main(){  
    RWCString s("What I tell you is true.");  
    // Create a substring and use it as an lvalue:  
    s(19, 0) = "three times ";  
    cout << s << endl;  
  }  

Program output:


  What I tell you is three times true.  

Assignment Operators

RWCSubString&
operator=(const RWCString&);
Assignment from an RWCString. The statements:
RWCString a;
RWCString b;
...
b(2, 3) = a;
will copy a's data into the substring b(2,3). The number of elements need not match: if they differ, b will be resized appropriately. Sets self's extent to be the length of the assigned RWCString. If self is the null substring, then the statement has no effect. Returns a reference to self.
RWCSubString&
operator=(const RWCSubString&);
Assignment from an RWCSubString. The statements:
RWCString a;
RWCString b;
...
b(2, 3) = a(5,5);
will copy 5 characters of a's data into the substring b(2,3). The number of elements need not match: if they differ, b will be resized appropriately. Sets self's extent to be the extent of the assigned RWCSubString. If self is the null substring, then the statement has no effect. Returns a reference to self.
RWCSubString&
operator=(const char*);
Assignment from a character string. Example:
RWCString str("Mary had a lamb");
char dat[] = "Perrier";
str(11,4) = dat;  // "Mary had a Perrier"
Note that the number of characters selected need not match: if they differ, str will be resized appropriately. Sets self's extent to be the strlen() of the assigned character string. If self is the null substring, then the statement has no effect. Returns a reference to self.

Indexing Operators

char&
operator[](size_t i);
char
operator[](size_t i) const;
Returns the ith character of the substring. The first variant can be used as an lvalue, the second cannot. The index i must be between zero and the length of the substring, less one. Bounds checking is performed: if the index is out of range, then an exception of type RWBoundsErr will occur.
char&
operator()(size_t i);
char
operator()(size_t i) const;
Returns the ith character of the substring. The first variant can be used as an lvalue, the second cannot. The index i must be between zero and the length of the substring, less one. Bounds checking is enabled by defining the pre-processor macro RWBOUNDS_CHECK before including <rw/cstring.h>. In this case, if the index is out of range, then an exception of type RWBoundsErr will occur.

Public Member Functions

RWBoolean
isNull() const;
Returns TRUE if this is a null substring.
size_t
length() const;
Returns the extent (i.e., length) of the RWCSubString.
RWBoolean
operator!() const;
Returns TRUE if this is a null substring.
size_t
start() const;
Returns the starting element of the RWCSubString.
void
toLower();
Changes all upper-case letters in self to lower-case. Uses the standard C library function tolower().
void
toUpper();
Changes all lower-case letters in self to upper-case. Uses the standard C library function toupper().

Global Logical Operators

RWBoolean
operator==(const RWCSubString&, const RWCSubString&);
RWBoolean
operator==(const RWCString&,    const RWCSubString&);
RWBoolean
operator==(const RWCSubString&, const RWCString&   );
RWBoolean
operator==(const char*,         const RWCSubString&);
RWBoolean
operator==(const RWCSubString&, const char*        );
Returns TRUE if the substring is lexicographically equal to the character string or RWCString argument. Case sensitivity is exact.
RWBoolean
operator!=(const RWCString&,    const RWCString&   );
RWBoolean
operator!=(const RWCString&,    const RWCSubString&);
RWBoolean
operator!=(const RWCSubString&, const RWCString&   );
RWBoolean
operator!=(const char*,         const RWCString&   );
RWBoolean
operator!=(const RWCString&,    const char*        );
Returns the negation of the respective operator==().
RWCTokenizer

RWCTokenizer

Synopsis

#include <rw/ctoken.h>
RWCString str("a string of tokens");
RWCTokenizer(str);  // Lex the above string

Description

Class RWCTokenizer is designed to break a string up into separate tokens, delimited by an arbitrary "white space." It can be thought of as an iterator for strings and as an alternative to the ANSI C function strtok() which has the unfortunate side effect of changing the string being tokenized.

Persistence

None

Example


  #include <rw/ctoken.h>  
  #include <rw/rstream.h>  
  main(){  
    RWCString a("Something is rotten in the state of Denmark");  
    RWCTokenizer next(a);           // Tokenize the string a  
    RWCString token;                // Will receive each token  
    // Advance until the null string is returned:  
    while (!(token=next()).isNull())  
      cout << token << "\n";  
  }  

Program output:


     Something  
     is  
     rotten  
     in  
     the  
     state  
     of  
     Denmark  

Public Constructor

RWCTokenizer(const RWCString& s);
Construct a tokenizer to lex the string s.

Public Member Operators

RWCSubString
operator();
Advance to the next token and return it as a substring. The tokens are delimited by any of the four characters in " \t\n\0". (space, tab, newline and null).
RWCSubString
operator()(const char* s);
Advance to the next token and return it as a substring. The tokens are delimited by any character in s, or any embedded null.
RWCSubString
operator()(const char* s,size_t num);
Advance to the next token and return it as a substring. The tokens are delimited by any of the first num characters in s. Buffer s may contain nulls, and must contain at least num characters. Tokens will not be delimited by nulls unless s contains nulls.
RWDate

RWDate

Synopsis

#include <rw/rwdate.h>RWDate a;   // Construct today's date

Description

Class RWDate represents a date, stored as a Julian day number. The member function isValid() can be used to determine whether an RWDate is a valid date. For example, isValid() would return FALSE for the date 29 February 1991 because 1991 is not a leap year. See "Using Class RWDate" in the Tools.h++ User's Guide.
RWDate's can be converted to and from RWTime's, and to and from the Standard C library type struct tm defined in <time.h>.
Note that using a 2-digit year specifier in your code may lead to less-than-perfect behavior at the turn of the century. We urge you to create programs that are "millenially correct" by using 4-digit year specifiers.
Note that because the default constructor for this class creates an instance holding the current date, constructing a large array of RWDate may be slow.
RWDate v[5000];     // Figures out the current date 5000 times
Those with access to the Standard C++ Library-based versions of the Tools.h++ template collections should consider the following:
// Figures out the current date just once:
RWTValOrderedVector<RWDate> v(5000, RWDate());
Thanks to the smart allocation scheme of the standard collections, the above declaration will result in only one call to the default constructor followed by 5000 invocations of the copy constructor. In the case of RWDate, the copy constructor amounts to an assignment of one long to another, resulting in faster creation than the simple array.

Persistence

Simple

Example


  #include <rw/rwdate.h>  
  #include <rw/rstream.h>  
  
  main(){  
    // Today's date  
    RWDate d;  
  
    // Last Sunday's date:  
    RWDate lastSunday = d.previous("Sunday");  
  
    cout << d << endl << lastSunday << endl;  
  }  

Program output:


  03/22/91  
  03/17/91  

Public Constructors

RWDate();
Default constructor. Constructs an RWDate with the present date.
RWDate(const RWDate&);
Copy constructor.
RWDate(unsigned day, unsigned year);
Constructs an RWDate with a given day of the year and a given year. The member function isValid() can be used to test whether the results are a valid date.
RWDate(unsigned day, unsigned month, unsigned year);
Constructs an RWDate with the given day of the month, month of the year, and year. Days should be 1-31, months should be 1-12, and the year may be specified as (for example) 1990, or 90. The member function isValid() can be used to test whether the results are a valid date.
RWDate(unsigned day, const char* mon, unsigned year,
       const RWLocale& locale = RWLocale::global());
Constructs an RWDate with the given day of the month, month and year. The locale argument is used to convert the month name. Days should be 1- 31, months may be specified as (for example): January, JAN, or Jan, and the year may be specified as (for example) 1990, or 90. The member function isValid() can be used to test whether the results are a valid date.
RWDate(istream& s,const RWLocale& locale =
       RWLocale::global());
A full line is read, and converted to a date by the locale argument. The member function isValid() must be used to test whether the results are a valid date. Because RWLocale cannot rigorously check date input, dates created in this way should also be reconfirmed by the user.
RWDate(const RWCString& str,
       const RWLocale& locale = RWLocale::global());
The string str is converted to a date. The member function isValid() must be used to test whether the results are a valid date. Because RWLocale cannot rigorously check date input, dates created in this way should also be reconfirmed by the user.
RWDate(const RWTime& t,
       const RWZone& zone = RWZone::local());
Constructs an RWDate from an RWTime. The time zone used defaults to local. The member function isValid() must be used to test whether the results are a valid date.
RWDate(const struct tm*);
Constructs an RWDate from the contents of the struct tm argument members tm_year, tm_mon, and tm_mday. Note that the numbering of months and years used in struct tm differs from that used for RWDate and RWTime operations. struct tm is declared in the standard include file <time.h>.
RWDate(unsigned long jd);
Construct a date from the Julian Day number jd. Note that it is possible to construct a valid RWDate which represents a day previous to the beginning of the Gregorian calendar for some locality. Rogue Wave doesn't know the specifics for your locality, so will not enforce an arbitrary cutoff for "validity."

Public Member Operators

RWDate&
operator=(const RWDate&);
Assignment operator.
RWDate
operator++();
Prefix increment operator. Adds one day to self, then return the result.
RWDate
operator--();
Prefix decrement operator. Subtracts one day from self, then returns the result.
RWDate
operator++(int);
Postfix increment operator. Adds one day to self, returning the initial value.
RWDate
operator--(int);
Postfix decrement operator. Subtracts one day from self, returning the initial value.
RWDate&
operator+=(unsigned long s);
Adds s days to self, returning self.
RWDate&
operator-=(unsigned long s);
Substracts s days from self, returning self.

Public Member Functions

RWCString
asString(char format = 'x',
         const RWLocale& = RWLocale::global()) const;
Returns the date as a string, formatted by the RWLocale argument. Formats are as defined in the standard C library function strftime().
RWCString
asString(const char* format,
         const RWLocale& = RWLocale::global()) const;
Returns the date as a string, formatted by the RWLocale argument. Formats are as defined in the standard C library function strftime().
RWBoolean
between(const RWDate& a, const RWDate& b) const;
Returns TRUE if this RWDate is between a and b, inclusive.
size_t
binaryStoreSize() const;
Returns the number of bytes necessary to store the object using the global function
RWFile& operator<<(RWFile&, const RWDate&);
int
compareTo(const RWDate* d) const;
Compares self to the RWDate pointed to by d and returns:
0 if self == *d;
1 if self > *d;
-1 if self < *d.
unsigned
day() const;
Returns the day of the year (1-366) for this date.
unsigned
dayOfMonth() const;
Returns the day of the month (1-31) for this date.
void
extract(struct tm*) const;
Returns with the struct tm argument filled out completely, with the time members set to 0 and tm_isdst set to -1. Note that the encoding for months and days of the week used in struct tm differs from that used elsewhere in RWDate. If the date is invalid, all fields are set to -1.
unsigned
firstDayOfMonth() const;
Returns the day of the year (1-366) corresponding to the first day of this RWDate's month and year.
unsigned
firstDayOfMonth(unsigned month) const;
Returns the day of the year (1-366) corresponding to the first day of the month month (1-12) in this RWDate's year.
unsigned
hash() const;
Returns a suitable hashing value.
RWBoolean
isValid() const;
Returns TRUE if this is a valid date, FALSE otherwise.
The following two functions are provided as a service to users who need to manipulate the date representation directly. The julian day number is not the Julian date!. The julian day number is calculated using Algorithm 199 from Communications of the ACM, Volume 6, No. 8, (Aug. 1963), p. 444 and is valid for any valid Gregorian date in the Gregorian calendar. The Gregorian calendar was first introduced on Sep. 14, 1752, and was adopted at various times in various places.
unsigned long
julian() const;
Returns the value of the julian day number..
void
julian(unsigned long j);
Changes the value of the julian day number to j.
RWBoolean
leap() const;
Returns TRUE if the year of this RWDate is a leap year.
RWDate
max(const RWDate& t) const;
Returns the later date of self or t.
RWDate
min(const RWDate& t) const;
Returns the earlier date of self or t.
unsigned
month() const;
Returns the month (1-12) for this date.
RWCString
monthName(const RWLocale& = RWLocale::global()) const;
Returns the name of the month for this date, according to the optional RWLocale argument.
RWDate
next(unsigned dayNum) const;
Returns the date of the next numbered day of the week, where Monday = 1, ..., Sunday = 7. The variable dayNum must be between 1 and 7, inclusive.
RWDate
next(const char* dayName,
     const RWLocale& = RWLocale::global()) const;
Returns the date of the next dayName (for example, the date of the previous Monday) The weekday name is interpreted according to the RWLocale argument.
RWDate
previous(unsigned dayNum) const;
Returns the date of the previous numbered day of the week, where Monday = 1, ..., Sunday = 7. The variable dayNum must be between 1 and 7, inclusive.
RWDate
previous(const char* dayName,
         const RWLocale& = RWLocale::global()) const;
Returns the date of the previous dayName (for example, the date of the previous Monday) The weekday name is interpreted according to the RWLocale argument.
RWCString
weekDayName(const RWLocale& = RWLocale::global()) const;
Returns the name of the day of the week for this date, according to the optional RWLocale argument.
unsigned
weekDay() const;
Returns the number of the day of the week for this date, where Monday = 1, ..., Sunday = 7.
unsigned
year() const;
Returns the year of this date.

Static Public Member Functions

static unsigned
dayOfWeek(const char* dayName,
          const RWLocale& = RWLocale::global());
Returns the number of the day of the week corresponding to the given dayName. "Monday" = 1, ..., "Sunday" = 7. Names are interpreted by the RWLocale argument. Returns 0 if no match is found.
static unsigned
daysInMonthYear(unsigned month, unsigned year);
Returns the number of days in a given month and year. Returns 0 if month is not between 1 and 12 inclusive.
static unsigned
daysInYear(unsigned year);
Returns the number of days in a given year.
static RWBoolean
dayWithinMonth(unsigned monthNum, unsigned dayNum,
               unsigned year);
Returns TRUE if a day (1-31) is within a given month in a given year.
static unsigned
hash(const RWDate& d);
Returns the hash value of d as returned by d.hash().
static unsigned
indexOfMonth(const char* monthName,
             const RWLocale& = RWLocale::global());
Returns the number of the month (1-12) corresponding to the given monthName. Returns 0 for no match.
static unsigned long
jday(unsigned mon, unsigned day, unsigned year);
Returns the Julian day corresponding to the given month (1-12), day (1-31) and year. Returns zero (0) if the date is invalid.
static RWCString
nameOfMonth(unsigned monNum,
            const RWLocale& = RWLocale::global());
Returns the name of month monNum (January = 1, ..., December = 12), formatted for the given locale.
static RWBoolean
leapYear(unsigned year);
Returns TRUE if a given year is a leap year.
static RWDate
now();
Returns today's date.
static RWCString
weekDayName(unsigned dayNum,
            const RWLocale& = RWLocale::global());
Returns the name of the day of the week dayNum (Monday = 1, ..., Sunday = 7), formatted for the given locale.

Related Global Operators

RWBoolean
operator<(const RWDate& d1, const RWDate& d2);
Returns TRUE if the date d1 is before d2.
RWBoolean
operator<=(const RWDate& d1, const RWDate& d2);
Returns TRUE if the date d1 is before or the same as d2.
RWBoolean
operator>(const RWDate& d1, const RWDate& d2);
Returns TRUE if the date d1 is after d2.
RWBoolean
operator>=(const RWDate& d1, const RWDate& d2);
Returns TRUE if the date d1 is after or the same as d2.
RWBoolean
operator==(const RWDate& d1, const RWDate& d2);
Returns TRUE if the date d1 is the same as t2.
RWBoolean
operator!=(const RWDate& d1, const RWDate& d2);
Returns TRUE if the date d1 is not the same as d2.
RWDate
operator+(const RWDate& d, unsigned long s);
RWDate
operator+(unsigned long s, const RWDate& d);
Returns the date s days in the future from the date d.
unsigned long
operator-(const RWDate& d1, const RWDate& d2);
If d1>d2, returns the number of days between d1 and d2. Otherwise, the result is implementation defined.
RWDate
operator-(const RWDate& d, unsigned long s);
Returns the date s days in the past from d.
ostream&
operator<<(ostream& s, const RWDate& d);
Outputs the date d on ostream s, according to the locale imbued in the stream (see class RWLocale), or by RWLocale::global() if none.
istream&
operator>>(istream& s, RWDate& t);
Reads t from istream s. One full line is read, and the string contained is converted according to the locale imbued in the stream (see class RWLocale), or by RWLocale::global() if none. The function RWDate::isValid() must be used to test whether the results are a valid date.
RWvostream&
operator<<(RWvostream&, const RWDate& date);
RWFile&
operator<<(RWFile&,     const RWDate& date);
Saves the date date to a virtual stream or RWFile, respectively.
RWvistream&
operator>>(RWvistream&, RWDate& date);
RWFile&
operator>>(RWFile&,     RWDate& date);
Restores the date into date from a virtual stream or RWFile, respectively, replacing the previous contents of date.
RWDDEstreambuf

RWDDEstreambuf

RWDDEstreambuf . RWCLIPstreambuf . streambuf

Synopsis

#include <rw/winstrea.h>
#include <iostream.h>
iostream str( new RWDDEstreambuf(CF_TEXT, TRUE, TRUE, TRUE) ) ;

Description

Class RWDDEstreambuf is a specialized streambuf that gets and puts sequences of characters to Microsoft Windows global memory that has been allocated with the GMEM_DDESHARE flag. It can be used to exchange data through the Windows Dynamic Data Exchange (DDE) facility.
The class has two modes of operation: dynamic and static. In dynamic mode, memory is allocated and reallocated on an as-needed basis. 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 by the DDE server. 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 by the DDE client.
In dynamic mode, the RWDDEstreambuf "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 RWDDEstreambuf destructor to free any allocated memory. After the call to str(), it becomes the user's responsibility.
In static mode, the user always 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.
Note that although the user may have the "responsibility" for freeing the memory, whether it is the client or the server that actually does the call to GlobalFree() will depend on the DDE "release" flag.

Persistence

None

Example

This is an example of how the class might be used by a DDE server.

  #include <rw/winstrea.h>  
  #include <iostream.h>  
  #include <windows.h>  
  #include <dde.h>  
  
  BOOL  
  postToDDE(HWND hwndServer, HWND hwndClient) {  
    RWDDEstreambuf* buf =  
    new RWDDEstreambuf(CF_TEXT, TRUE, TRUE, TRUE);  
    ostream ostr(buf);  
    double d = 12.34;  
    ostr << "Some text to be exchanged through the DDE.\n";  
    ostr << "The double you requested is: " << d << endl;  
    ostr.put(0);// Include the terminating null  
    // Lock the streambuf, get its handle:  
    HANDLE hMem = buf->str();  
    // Get an identifying atom:  
    ATOM aItem = GlobalAddAtom("YourData");  
    if(!PostMessage(hwndClient, WM_DDE_DATA, hwndServer,  
                    MAKELONG(hMem, aItem))){  
      // Whoops!  The message post failed, perhaps because  
      // the client terminated.  Now we are responsible  
      // for deallocating the memory:  
     if( hMem != NULL )  
     GlobalFree(hMem);  
     GlobalDeleteAtom(aItem);  
     return FALSE;  
    }  
    return TRUE;  
  }  
The handle of the DDE server is passed in as parameter hwndServer, the handle of the client as parameter hwndClient. An ostream is created, using an RWDDEstreambuf as its associated streambuf. The results can be used much like any other ostream, such as cout, except that characters will be inserted into Windows global memory, from where they can be transferred through the DDE. Note the parameters used in the constructor. These should be studied below as they have important ramifications on how memory allocations are handled through the DDE. In particular, parameter fRelease, if TRUE, states
that the client will be responsible for deallocating the memory when done. The defaults also specify fAckReq TRUE, meaning that the client will acknowledge receiving the message: you must be prepared to receive it.
Some text and a double is inserted into the ostream. Member function str() is then called which unlocks and returns a Windows HANDLE. Once we have called str(), we are responsible for this memory and must either free it when done, or pass on that responsibility to someone else. In this case, it will be passed on to the client.
An atom is then constructed to identify the data. The DDE data, along with its identifying atom, is then posted. If the post fails, then we have been unable to foist our responsbility for the global memory onto someone else and will have to free it (along with the atom) ourselves.

Public Constructors

RWDDEstreambuf(WORD cfFormat  = CF_TEXT,
               BOOL fResponse = TRUE
               BOOL fAckReq   = TRUE
               BOOL fRelease  = TRUE);
Constructs an empty RWDDEstreambuf 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.
The four parameters are as defined by the Windows Reference, Volume 2 (in particular, see the section DDE Message Directory). Parameter cfFormat specifies the format of the data being inserted into the streambuf. These formats are the same as used by SetClipboardData(). If a specializing virtual streams class such as RWbostream or RWpostream is used to perform the actual character insertions instead of a simple ostream, the format may not be so simple. In this case, the user might want to register his or her own format, using the Windows function RegisterClipboardFormat().
For the meaning of the other three parameters see below, and/or the Windows reference manuals.
RWDDEstreambuf(HANDLE hMem);
Constructs an RWDDEstreambuf in static mode, using the memory block with global handle hMem. The effect of gets and puts beyond the size of this block is unspecified. The format of the DDE transfer, and the specifics of DDE acknowledgments, memory allocations, etc., can be obtained by using the member functions defined below.

Public Destructor

~RWDDEstreambuf();
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 RWDDEstreambuf inherits from streambuf, any of the latter's member functions can be used. Furthermore, RWDDEstreambuf has been designed to be analogous to streambuf. However, note that the return type of str() is a HANDLE, rather than a char*.
BOOL
ackReq() const;
Returns whether this DDE exchange requests an acknowledgement. See the Windows Reference, Volume 2, for more information.
WORD
format() const;
Returns the format of this DDE exchange (e.g., CF_TEXT for text exchange, etc.). See the Windows Reference, Volume 2, for more information.
BOOL
release() const;
Returns TRUE if the client is responsible for the release of of the memory returned by str(). See the Windows Reference, Volume 2, for more information.
BOOL
response() const;
Returns TRUE if this data is in response to a WM_DDE_REQUEST message. Otherwise, it is in response to a WM_DDE_ADVISE message. See the Windows Reference, Volume 2, for more information.
HANDLE
str();
Returns an (unlocked) HANDLE to the global memory being used. The RWDDEstreambuf should now be regarded as "frozen": the effect of inserting any more characters is undefined. If the RWDDEstreambuf 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 RWDDEstreambuf.
RWDiskPageHeap

RWDiskPageHeap

RWDiskPageHeap . RWBufferedPageHeap . RWVirtualPageHeap

Synopsis

#include <rw/diskpage.h>
unsigned nbufs;
unsigned pagesize;
RWDiskPageHeap heap("filename", nbufs, pagesize) ;

Description

Class RWDiskPageHeap is a specializing type of buffered page heap. It swaps its pages to disk as necessary.

Persistence

None

Example

In this example, 100 nodes of a linked list are created and strung together. The list is then walked, confirming that it contains 100 nodes. Each node is a single page. The "pointer" to the next node is actually the handle for the next page..

  #include <rw/diskpage.h>  
  #include <rw/rstream.h>  
  
  struct Node {  
    int key;  
    RWHandlenext;  
  };  
  
  RWHandle head = 0;  
  const int N = 100;  // Exercise 100 Nodes  
  
  main() {  
    // Construct a disk-based page heap with page size equal  
    // to the size of Node and with 10 buffers:  
    RWDiskPageHeap heap(0, 10, sizeof(Node));  
  
    // Build the linked list:  
    for (int i=0; i<N; i++){  
      RWHandle h = heap.allocate();  
      Node* newNode = (Node*)heap.lock(h);  
      newNode->key  = i;  
      newNode->next = head;  
      head = h;  
      heap.dirty(h);  
      heap.unlock(h);  
    }  
  // Now walk the list:  
  unsigned count = 0;  
  RWHandle nodeHandle = head;  
  while(nodeHandle){  
  Node* node = (Node*)heap.lock(nodeHandle);  
  RWHandle nextHandle = node->next;  
  heap.unlock(nodeHandle);  
  heap.deallocate(nodeHandle);  

  nodeHandle = nextHandle;  
  count++;  
    }  
  
  cout << "List with " << count << " nodes walked.\n";  
  return 0;  
  }  

Program output:


  List with 100 nodes walked.  

Public Constructor

RWDiskPageHeap(const char* filename = 0,
               unsigned nbufs       = 10,
               unsigned pgsize      = 512);
Constructs a new disk-based page heap. The heap will use a file with filename filename, otherwise it will negotiate with the operating system for a temporary filename. The number of buffers, each the size of the page size, will be nbufs. No more than this many pages can be locked at any one time. The size of each page is given by pgsize. To see whether a valid RWDiskPageHeap has been constructed, call member function isValid().

Public Destructor

virtual
~RWDiskPageHeap();
Returns any resources used by the disk page heap back to the operating system. All pages should have been deallocated before the destructor is called.

Public Member Functions

virtual RWHandle
allocate();
Redefined from class RWVirtualPageHeap. Allocates a page off the disk page heap and returns a handle for it. If there is no more space (for example, the disk is full) then returns zero.
virtual void
deallocate(RWHandle h);
Redefined from class RWBufferedPageHeap. Deallocate the page associated with handle h. It is not an error to deallocate a zero handle.
virtual void
dirty(RWHandle h);
Inherited from RWBufferedPageHeap.
RWBoolean
isValid() const;
Returns TRUE if this is a valid RWDiskPageHeap.
virtual void*
lock(RWHandle h);
Inherited from RWBufferedPageHeap.
virtual void
unlock(RWHandle h);
Inherited from RWBufferedPageHeap.
RWDlistCollectables

RWDlistCollectables

RWDlistCollectables . RWSequenceable . RWCollection . RWCollectable

Synopsis

#include <rw/dlistcol.h>
RWDlistCollectables a;

Description

Class RWDlistCollectables represents a group of ordered items, not accessible by an external key. Duplicates are allowed. The ordering of elements is determined externally, generally by the order of insertion and removal. An object stored by RWDlistCollectables must inherit abstract base class RWCollectable.
Class RWDlistCollectables is implemented as a doubly-linked list, which allows for efficient insertion and removal, as well as for movement in either direction.

Persistence

Polymorphic

Public Constructors

RWDlistCollectables();
Constructs an empty doubly-linked list.
RWDlistCollectables (RWCollectable* a);
Constructs a linked list with a single item a.

Public Member Operators

RWBoolean
operator==(const RWDlistCollectables& d) const;
Returns TRUE if self and d have the same number of items and if for every item in self, the corresponding item in the same position in d isEqual to it.

Public Member Functions

virtual Collectable*
append(RWCollectable*);
Redefined from RWSequenceable. Inserts the item at the end of the collection and returns it. Returns nil if the insertion was unsuccesful.
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 first to last.
virtual RWCollectable*&
at(size_t i);
virtual const RWCollectable*
at(size_t i) const;
Redefined from class RWSequenceable. The index must be between zero and the number of items in the collection less one, or an exception of type RWBoundsErr will occur. Note that for a linked list, these functions must traverse all the links, making them not particularly efficient.
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.
RWBoolean
containsReference(const RWCollectable* e) const;
Returns true if the list contains an item that is identical to the item pointed to by e (that is, that has the address e).
virtual size_t
entries() const;
Redefined from class RWCollection.
virtual RWCollectable*
find(const RWCollectable* target) const;
Redefined from class RWCollection. The first item that isEqual to the item pointed to by target is returned, or nil if no item is found.
RWCollectable*
findReference(const RWCollectable* e) const;
Returns the first item that is identical to the item pointed to by e (that is, that has the address e), or nil if none is found.
virtual RWCollectable*
first() const;
Redefined from class RWSequenceable. Returns the item at the beginning of the list.
RWCollectable*
get();
Returns and removes the item at the beginning of the list.
virtual unsigned
hash() const;
Inherited from class RWCollectable.
virtual size_t
index(const RWCollectable* c) const;
Redefined from class RWSequenceable. Returns the index of the first item that isEqual to the item pointed to by c, or RW_NPOS if there is no such index.
virtual RWCollectable*
insert(RWCollectable* c);
Redefined from class RWCollection. Adds the item to the end of the collection and returns it. Returns nil if the insertion was unsuccessful.
void
insertAt(size_t indx, RWCollectable* e);
Redefined from class RWSequenceable. Adds a new item to the collection at position indx. The item previously at position i is moved to i+1, etc. The index indx must be between 0 and the number of items in the collection, or an exception of type RWBoundsErr will occur.
virtual RWClassID
isA() const;
Redefined from class RWCollectable to return __RWDLISTCOLLECTABLES.
virtual RWBoolean
isEmpty() const;
Redefined from class RWCollection.
virtual RWCollectable*
last() const;
Redefined from class RWSequenceable. Returns the item at the end of the list.
virtual size_t
occurrencesOf(const RWCollectable* target) const;
Redefined from class RWCollection. Returns the number of items that isEqual to the item pointed to by target.
size_t
occurrencesOfReference(const RWCollectable* e) const;
Returns the number of items that are identical to the item pointed to by e (that is, that have the address e).
virtual RWCollectable*
prepend(RWCollectable*);
Redefined from class RWSequenceable. Adds the item to the beginning of the collection and returns it. Returns nil if the insertion was unsuccessful.
virtual RWCollectable*
remove(const RWCollectable* target);
Redefined from class RWCollection. Removes and returns the first item that isEqual to the item pointed to by target. Returns nil if there is no such item.
virtual void
removeAndDestroy(const RWCollectable* target);
Inherited from class RWCollection.
RWCollectable*
removeReference(const RWCollectable* e);
Removes and returns the first item that is identical to the item pointed to by e (that is, that has the address e). Returns nil if there is no such item.
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.
RWDlistCollectablesIterator

RWDlistCollectablesIterator

RWDlistCollectablesIterator . RWIterator

Synopsis

#include <rw/dlistcol.h>
RWDlistCollectables d;
RWDlistCollectablesIterator it(d) ;

Description

Iterator for class RWDlistCollectables. Traverses the linked-list from the first (head) to the last (tail) item. Functions are provided for moving in either direction.
As with all Rogue Wave iterators, the "current item" is undefined immediately after construction -- you must define it by using operator() or some other (valid) operation.
Once the iterator has advanced beyond the end of the collection it is no longer valid -- continuing to use it will bring undefined results.

Persistence

None

Public Constructor

RWDlistCollectablesIterator (RWDlistCollectables& d);
Construct an RWDlistCollectablesIterator from an RWDlistCollectables. Immediately after construction, the position of the iterator is undefined.

Public Member Operators

virtual RWCollectable*
operator()();
Redefined from class RWIterator. Advances the iterator to the next item and returns it. Returns nil when the end of the list is reached.
void
operator++();
Advances the iterator one item.
void
operator--();
Moves the iterator back one item.
void
operator+=(size_t n);
Advances the iterator n items.
void
operator-=(size_t n);
Moves the iterator back n items.

Public Member Functions

RWBoolean
atFirst() const;
Returns TRUE if the iterator is at the beginning of the list, otherwise FALSE;
RWBoolean
atLast() const;
Returns TRUE if the iterator is at the end of the list, otherwise FALSE;
virtual RWCollectable*
findNext(const RWCollectable* target);
Redefined from class RWIterator. Moves iterator to the next item which isEqual to the item pointed to by target and returns it. If no item is found, returns nil and the position of the iterator will be undefined.
RWCollectable*
findNextReference(const RWCollectable* e);
Moves iterator to the next item which is identical to the item pointed to by e (that is, that has address e) and returns it. If no item is found, returns nil and the position of the iterator will be undefined.
RWCollectable*
insertAfterPoint(RWCollectable* a);
Insert item a after the current cursor position and return the item. The cursor's position will be unchanged.
virtual RWCollectable*
key() const;
Redefined from class RWIterator. Returns the item at the current iterator position.
RWCollectable*
remove();
Removes and returns the item at the current cursor position. Afterwards, the iterator will be positioned at the previous item in the list.
RWCollectable*
removeNext(const RWCollectable* target);
Moves iterator to the next item in the list which isEqual to the item pointed to by target, removes it from the list and returns it. Afterwards, the iterator will be positioned at the previous item in the list. If no item is found, returns nil and the position of the iterator will be undefined.
RWCollectable*
removeNextReference(const RWCollectable* e);
Moves iterator to the next item in the list which is identical to the item pointed to by e (that is, that has address e), removes it from the list and returns it. Afterwards, the iterator will be positioned at the previous item in the list. If no item is found, returns nil and the position of the iterator will be undefined.
virtual void
reset();
Redefined from class RWIterator. Resets the iterator. Afterwards, the position of the iterator will be undefined.
void
toFirst();
Moves the iterator to the beginning of the list.
void
toLast();
Moves the iterator to the end of the list.
RWeistream

RWeistream

... . ios RWeistream . RWbistream ...
... . RWvistream . RWvios

Synopsis

#include <rw/estream.h>
RWeistream estr(cin);           // Construct an RWeistream,
                                // using cin's streambuf

Description

Class RWeistream specializes the base class RWbistream to restore values previously stored by RWeostream. The endian streams, RWeistream and RWeostream, offer an efficient compromise between the portable streams (RWpistream, RWpostream) and the binary streams (RWbistream, RWbostream). By compensating for differences in big-endian vs. little-endian formats, as well as sizes of the various integral types, the endian streams offer portability without incurring the stream-size overhead of translating values into a series of printable characters. For example, data stored in little-endian format by an RWeostream object in a DOS program can be retrieved by an RWeistream object on any of several machines, regardless of its native endian format or the sizes of its integral types. Endian streams will work properly when shared among a group of platforms that:
  • Share a common size and representation (apart from endian format) for types float and double;
  • Use two's complement format for negative integral values.
As with the portable streams, care must be taken when storing or retrieving variables of type char. Endian stream methods treat chars as numbers except where the method description explicitly states that the char is being treated, instead, as a character. See the entry for RWpostream for an example of this distinction. Data stored in an integral type on one platform may be too large to fit into that type on a receiving platform. If so, the RWeistream's failbit will be set.
Endian streams can be interrogated as to the stream state using member functions good(), bad(), eof(), etc.

Persistence

None.

Example

See RWeostream for an example of how the file "data.dat" might be created.

  #include <rw/estream.h>  
  #include <fstream.h>  
  main()  
  {  
   ifstream fstr("data.dat");     // Open an input file  
   RWeistream estr(fstr);       // Construct an RWeistream from it  
                                // (For DOS: RWeistream estr(fstr, ios::binary)  
   int i;  
   float f;  
   double d;  
  
   estr >> i;                   // Restore an int that was stored in binary,  
                               //  without regard to size or endian format.  
   estr >> f >> d;             //  Restore a float & double without regard to  
                               //  endian formats.  
  }  

Public Constructors

RWeistream(streambuf* s);
Construct an RWeistream from the streambuf s. For DOS, this streambuf must have been created in binary mode. Throw exception RWStreamErr if not a valid endian stream.
RWeistream(istream& str);
Construct an RWeistream using the streambuf associated with the istream str. For DOS, the str must have been opened in binary mode. Throw exception RWStreamErr if not a valid endian stream.

Public Member Functions

virtual int
get();
virtual RWvistream&
get(char& c);
virtual RWvistream&
get(unsigned char& c);
virtual RWvistream&
get(char* v, size_t N);
virtual RWvistream&
get(unsigned char* v, size_t N);
Inherited from class RWbistream.
virtual RWvistream&
get(wchar_t& wc);
Redefined from class RWbistream. Get the next wchar_t from the input stream and store it in wc, compensating for any differences in size or endian format between the stream and the current environment. Set the failbit if the value in the stream is too large to be stored in wc.
virtual RWvistream&
get(wchar_t* v, size_t N);
Redefined from class RWbistream. Get a vector of wchar_ts and store it in the array beginning at v, compensating for any differences in size or endian format between the stream and the current environment. If the restore stops prematurely, store whatever possible in v, and set the failbit. Also set the failbit if any values in the stream are too large to be stored in an element of v.
virtual RWvistream&
get(double* v, size_t N);
Redefined from class RWbistream. Get a vector of doubles and store them in the array beginning at v, compensating for any difference in endian format between the stream and the current environment. If the restore stops prematurely, store whatever possible in v, and set the failbit.
virtual RWvistream&
get(float* v, size_t N);
Redefined from class RWbistream. Get a vector of floats and store them in the array beginning at v, compensating for any difference in endian format between the stream and the current environment. If the restore stops prematurely, store whatever possible in v, and set the failbit.
virtual RWvistream&
get(int* v, size_t N);
Redefined from class RWbistream. Get a vector of ints and store them in the array beginning at v, compensating for any differences in size or endian format between the stream and the current environment. If the restore stops prematurely, store whatever possible in v, and set the failbit. Also set the failbit if any values in the stream are too large to be stored in an element of v.
virtual RWvistream&
get(long* v, size_t N);
Redefined from class RWbistream. Get a vector of longs and store them in the array beginning at v, compensating for any differences in size or endian format between the stream and the current environment. If the restore stops prematurely, store whatever possible in v, and set the failbit. Also set the failbit if any values in the stream are too large to be stored in an element of v.
virtual RWvistream&
get(short* v, size_t N);
Redefined from class RWbistream. Get a vector of shorts and store them in the array beginning at v, compensating for any differences in size or endian format between the stream and the current environment. If the restore stops prematurely, store whatever possible in v, and set the failbit. Also set the failbit if any values in the stream are too large to be stored in an element of v.
virtual RWvistream&
get(unsigned short* v, size_t N);
Redefined from class RWbistream. Get a vector of unsigned shorts and store them in the array beginning at v. If the restore stops prematurely, store whatever possible in v, and set the failbit. Also set the failbit if any values in the stream are too large to be stored in an element of v.
virtual RWvistream&
get(unsigned int* v, size_t N);
Redefined from class RWbistream. Get a vector of unsigned ints and store them in the array beginning at v, compensating for any differences in size or endian format between the stream and the current environment. If the restore stops prematurely, store whatever possible in v, and set the failbit. Also set the failbit if any values in the stream are too large to be stored in an element of v.
virtual RWvistream&
get(unsigned long* v, size_t N);
Redefined from class RWbistream. Get a vector of unsigned longs and store them in the array beginning at v, compensating for any differences in size or endian format between the stream and the current environment If the restore stops prematurely, store whatever possible in v, and set the failbit. Also set the failbit if any values in the stream are too large to be stored in an element of v.
virtual RWvistream&
getString(char* s, size_t N);
Redefined from class RWbistream. Restores a character string from the input stream and stores it in the array beginning at s. The function stops reading at the end of the string or after N-1 characters, whichever comes first. If the latter, then the failbit of the stream will be set, and the remaining characters of the string will be extracted from the stream and thrown away. In either case, the string will be terminated with a null byte. If the size of the string is too large to be represented by a variable of type size_t in the current environment, the badbit of the stream will be set, and no characters will be extracted. Note that the elements of the string are treated as characters, not numbers.
virtual RWvistream&
operator>>(char& c);
Redefined from class RWbistream. Get the next char from the input stream and store it in c. Note that c is treated as a character, not a number.
virtual RWvistream&
operator>>(wchar_t& wc);
Redefined from class RWbistream. Get the next wchar_t from the input stream and store it in wc, compensating for any differences in size or endian format between the stream and the current environment. Set the failbit if the value in the stream is too large to be stored in wc.
virtual RWvistream&
operator>>(double& d);
Redefined from class RWbistream. Get the next double from the input stream and store it in d, compensating for any difference in endian format between the stream and the current environment.
virtual RWvistream&
operator>>(float& f);
Redefined from class RWbistream. Get the next float from the input stream and store it in f, compensating for any difference in endian format between the stream and the current environment.
virtual RWvistream&
operator>>(int& i);
Redefined from class RWbistream. Get the next int from the input stream and store it in i, compensating for any differences in size or endian format between the stream and the current environment. Set the failbit if the value in the stream is too large to be stored in i.
virtual RWvistream&
operator>>(long& l);
Redefined from class RWbistream. Get the next long from the input stream and store it in l, compensating for any differences in size or endian format between the stream and the current environment. Set the failbit if the value in the stream is too large to be stored in l.
virtual RWvistream&
operator>>(short& s);
Redefined from class RWbistream. Get the next short from the input stream and store it in s, compensating for any differences in size or endian format between the stream and the current environment. Set the failbit if the value in the stream is too large to be stored in s.
virtual RWvistream&
operator>>(unsigned char& c);
Redefined from class RWbistream. Get the next unsigned char from the input stream and store it in c. Note that c is treated as a character, not a number.
virtual RWvistream&
operator>>(unsigned short& s);
Redefined from class RWbistream. Get the next unsigned short from the input stream and store it in s, compensating for any differences in size or endian format between the stream and the current environment. Set the failbit if the value in the stream is too large to be stored in s.
virtual RWvistream&
operator>>(unsigned int& i);
Redefined from class RWbistream. Get the next unsigned int from the input stream and store it in i, compensating for any differences in size or endian format between the stream and the current environment. Set the failbit if the value in the stream is too large to be stored in i.
virtual RWvistream&
operator>>(unsigned long& l);
Redefined from class RWbistream. Get the next unsigned long from the input stream and store it in l, compensating for any differences in size or endian format between the stream and the current environment. Set the failbit if the value in the stream is too large to be stored in l.
RWeostream::EndianstreamEndian();
Return the endian format (RWeostream::BigEndian or RWeostream::LittleEndian) of numeric values, as represented in the stream.
size_t
streamSizeofInt();
Return the size of ints, as represented in the stream.
size_t
streamSizeofLong();
Return the size of longs, as represented in the stream.
size_t
streamSizeofShort();
Return the size of shorts, as represented in the stream.
size_t
streamSizeofSizeT();
Return the size of size_ts, as represented in the stream.
size_t
streamSizeofWchar();
Returns the size of wchar_ts, as represented in the stream.
RWeostream

RWeostream

... . ios
RWeostream ... ...

. RWbostream . RWvostream . RWvios

Synopsis

#include <rw/estream.h>
// Construct an RWeostream that uses cout's streambuf,
//   and writes out values in little-endian format:
RWeostream estr(cout, RWeostream::LittleEndian);

Description

Class RWeostream specializes the base class RWbostream to store values in a portable binary format. The results can be restored via its counterpart, RWeistream. See the entry for RWeistream for a general description of the endian stream classes.

Persistence

None.

Example

See RWeistream for an example of how the file "data.dat" might be read.

  #include <rw/estream.h>  
  #include <fstream.h>  
  
  main()  
  {  
   ofstream fstr("data.dat");                        // Open an output file  
   RWeostream estr(fstr);                // Construct an RWeostream from it  
                            // (For DOS: RWeistream estr(fstr, ios::binary)  
   int i = 5;  
   float f = 22.1;  
   double d = -0.05;  
  
   estr << i;                            // Store an int, float, and double  
   estr << f << d;                       //  using the native endian format  
  }  

Enumeration

enum RWeostream::Endian { LittleEndian,
                          BigEndian,
                          HostEndian }
Used to specify the format that RWeostreams should use to represent numeric values in the stream. HostEndian means to use the native format of the current environment.

Public Constructors

RWeostream(streambuf* s, Endian fmt = HostEndian);
Construct an RWeostream from the streambuf s. Values placed into the stream will have an endian format given by fmt. For DOS, the streambuf must have been created in binary mode. Throw exception RWStreamErr if streambuf s is not empty.
RWeostream(ostream& str, Endian fmt = HostEndian);
Construct an RWeostream from the streambuf associated with the output stream str. Values placed into the stream will have an endian format given by fmt. For DOS, the str must have been opened in binary mode. Throw exception RWStreamErr if streambuf s is not empty.

Public Destructor

virtual ~RWvostream();
This virtual destructor allows specializing classes to deallocate any resources that they may have allocated.

Public Member Functions

virtual RWvostream&
flush();
Send the contents of the stream buffer to output immediately.
virtual RWvostream&
operator<<(const char* s);
Redefined from class RWbostream. Store the character string starting at s to the output stream. The character string is expected to be null terminated. Note that the elements of s are treated as characters, not as numbers.
virtual RWvostream&
operator<<(char c);
Redefined from class RWbostream. Store the char c to the output stream. Note that c is treated as a character, not a number.
virtual RWvostream&
operator<<(wchar_t wc);
Redefined from class RWbostream. Store the wchar_t wc to the output stream in binary, using the appropriate endian representation.
virtual RWvostream&
operator<<(unsigned char c);
Redefined from class RWbostream. Store the unsigned char c to the output stream. Note that c is treated as a character, not a number.
virtual RWvostream&
operator<<(double d);
Redefined from class RWbostream. Store the double d to the output stream in binary, using the appropriate endian representation.
virtual RWvostream&
operator<<(float f);
Redefined from class RWbostream. Store the float f to the output stream in binary, using the appropriate endian representation.
virtual RWvostream&
operator<<(int i);
Redefined from class RWbostream. Store the int i to the output stream in binary, using the appropriate endian representation.
virtual RWvostream&
operator<<(unsigned int i);
Redefined from class RWbostream. Store the unsigned int i to the output stream in binary, using the appropriate endian representation.
virtual RWvostream&
operator<<(long l);
Redefined from class RWbostream. Store the long l to the output stream in binary, using the appropriate endian representation.
virtual RWvostream&
operator<<(unsigned long l);
Redefined from class RWbostream. Store the unsigned long l to the output stream in binary, using the appropriate endian representation.
virtual RWvostream&
operator<<(short s);
Redefined from class RWbostream. Store the short s to the output stream in binary, using the appropriate endian representation.
virtual RWvostream&
operator<<(unsigned short s);
Redefined from class RWbostream. Store the unsigned short s to the output stream in binary, using the appropriate endian representation.
virtual RWvostream&
put(char c);
virtual RWvostream&
put(unsigned char c);
virtual RWvostream&
put(const char* p, size_t N);
Inherited from class RWbostream.
virtual RWvostream&
put(wchar_t wc);
Redefined from class RWbostream. Store the wchar_t wc to the output stream in binary, using the appropriate endian representation.
virtual RWvostream&
put(const wchar_t* p, size_t N);
Redefined from class RWbostream. Store the vector of wchar_ts starting at p to the output stream in binary, using the appropriate endian representation.
virtual RWvostream&
put(const unsigned char* p, size_t N);
Redefined from class RWbostream. Store the vector of unsigned chars starting at p to the output stream in binary, using the appropriate endian representation.
virtual RWvostream&
put(const short* p, size_t N);
Redefined from class RWbostream. Store the vector of shorts starting at p to the output stream in binary, using the appropriate endian representation.
virtual RWvostream&
put(const unsigned short* p, size_t N);
Redefined from class RWbostream. Store the vector of unsigned shorts starting at p to the output stream in binary, using the appropriate endian representation.
virtual RWvostream&
put(const int* p, size_t N);
Redefined from class RWbostream. Store the vector of ints starting at p to the output stream in binary, using the appropriate endian representation.
virtual RWvostream&
put(const unsigned int* p, size_t N);
Redefined from class RWbostream. Store the vector of unsigned ints starting at p to the output stream in binary, using the appropriate endian representation.
virtual RWvostream&
put(const long* p, size_t N);
Redefined from class RWbostream. Store the vector of longs starting at p to the output stream in binary, using the appropriate endian representation.
virtual RWvostream&
put(const unsigned long* p, size_t N);
Redefined from class RWbostream. Store the vector of unsigned longs starting at p to the output stream in binary, using the appropriate endian representation.
virtual RWvostream&
put(const float* p, size_t N);
Redefined from class RWbostream. Store the vector of floats starting at p to the output stream in binary, using the appropriate endian representation.
virtual RWvostream&
put(const double* p, size_t N);
Redefined from class RWbostream. Store the vector of doubles starting at p to the output stream in binary, using the appropriate endian representation.
virtual RWvostream&
putString(const char*s, size_t N);
Store the character string, including embedded nulls, starting at s to the output string.
RWFactory

RWFactory

Synopsis

typedef unsigned short  RWClassID;
typedef RWCollectable*  (*RWuserCreator)();
#include <rw/factory.h>

RWFactory* theFactory;

Description

Class RWFactory can create an instance of an RWCollectable object, given a class ID. It does this by maintaining a table of class IDs and associated "creator functions." A creator function has prototype:
RWCollectable*     aCreatorFunction();
This function should create an instance of a particular class. For a given RWClassID tag, the appropriate function is selected, invoked and the resultant pointer returned. Because any object created this way is created off the heap, you are responsible for deleting it when done.
There is a one-of-a-kind global RWFactory which can be accessed using getRWFactory. It is guaranteed to have creator functions in it for all of the classes referenced by your program. See also the section in the User's Guide about RWFactory.

Persistence

None

Example


  #include <rw/factory.h>  
  #include <rw/rwbag.h>  
  #include <rw/colldate.h>  
  #include <rw/rstream.h>  
  
  main(){  
   // Create new RWBag off the heap, using Class ID __RWBAG.  
  
   RWBag* b = (RWBag*)getRWFactory ()-> create(__RWBAG);  
  
   b->insert( new RWCollectableDate ); // Insert today's date  
   // ...  
   b->clearAndDestroy();     // Cleanup: first delete members,  
   delete b;                 // then the bag itself  
  }  
  END FILE  

Public Constructors

RWFactory();
Construct an RWFactory.

Public Operator

RWBoolean
operator<=(const RWFactory& h);
Returns TRUE if self is a subset of h, that is, every element of self has a counterpart in h which isEqual. This operator is included to fix an inconsistency in the C++ language. It is not explicitly present unless you are compiling with an implementation of the Standard C++ Library. It would normally be inherited from RWSet

Note - If you inherit from RWFactory 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.

Public Member Functions

void
addFunction(RWuserCreator uc, RWClassID id);
Adds to the RWFactory the global function pointed to by uc, which creates an instance of an object with RWClassID id.
void
addFunction(RWuserCreator uc, RWClassID id, RWStringID sid);
Adds to the RWFactory the global function pointed to by uc, which creates an instance of an object with RWClassID id and RWStringID sid.
RWCollectable*
create(RWClassID id) const;
Allocates a new instance of the class with RWClassID id off the heap and returns a pointer to it. Returns nil if id does not exist. Because this instance is allocated off the heap, you are responsible for deleting it when done.
RWCollectable*
create(RWString sid) const;
Allocates a new instance of the class with RWStringID sid off the heap and returns a pointer to it. Returns nil if sid does not exist. Because this instance is allocated off the heap, you are responsible for deleting it when done.
RWuserCreator
getFunction(RWClassID id) const;
Returns from the RWFactory a pointer to the global function associated with RWClassID id. Returns nil if id does not exist.
RWuserCreator
getFunction(RWStringID sid) const;
Returns from the RWFactory a pointer to the global function associated with RWStringID sid. Returns nil if sid does not exist.
void
removeFunction(RWClassID id);
Removes from the RWFactory the global function associated with RWClassID id. If id does not exist in the factory, no action is taken.
void
removeFunction(RWStringID sid);
Removes from the RWFactory the global function associated with RWStringID sid. If sid does not exist in the factory, no action is taken.
RWStringID
stringID(RWClassID id) const;
Looks up the RWStringID associated with id and returns it. If there is no such association, returns RWStringID("NoID").
RWClassID
classID(RWStringID) const;
Looks up the RWClassID associated with sid and returns it. If there is no such association, returns __RWUNKNOWN.
RWFile

RWFile

Synopsis

#include <rw/rwfile.h>
RWFile f("filename");

Description

Class RWFile encapsulates binary file operations using the Standard C stream library (functions fopen(), fread(), fwrite(), etc.). This class is based on class PFile of the Interviews Class Library (1987, Stanford University). The member function names begin with upper case letters in order to maintain compatibility with class PFile .
Because this class is intended to encapsulate binary operations, it is important that it be opened using a binary mode. This is particularly important under MS-DOS -- otherwise bytes that happen to match a newline will be expanded to (carriage return, line feed).

Persistence

None

Public Constructors

RWFile(const char* filename, const char* mode = 0);
Construct an RWFile to be used with the file of name filename and with mode mode. The mode is as given by the Standard C library function fopen(). If mode is zero (the default) then the constructor will attempt to open an existing file with the given filename for update (mode "rb+"). If this is not possible, then it will attempt to create a new file with the given filename (mode "wb+"). The resultant object should be checked for validity using function isValid().
~RWFile();
Performs any pending I/O operations and closes the file.

Public Member Functions

const char*
Access();
Returns the access mode with which the underlying FILE* was opened.
void
ClearErr();
Reset error state so that neither Eof() nor Error() returns TRUE. Calls C library function clearerr().
RWoffset
CurOffset();
Returns the current position, in bytes from the start of the file, of the file pointer.
RWBoolean
Eof();
Returns TRUE if an end-of-file has been encountered.
RWBoolean
Erase();
Erases the contents but does not close the file. Returns TRUE if the operation was successful.
RWBoolean
Error();
Returns TRUE if a file I/O error has occurred as determined by a call to the C library function ferror().
RWBoolean
Exists();
Returns TRUE if the file exists.
RWBoolean
Flush();
Perform any pending I/O operations. Returns TRUE if successful.
const char*
GetName();
Returns the file name.
FILE*
GetStream();
Returns the FILE* that underlies the RWFile interface. Provided for users who need to "get under the hood" for system-dependent inquiries, etc. Do not use to alter the state of the file!
RWBoolean
IsEmpty();
Returns TRUE if the file contains no data, FALSE otherwise.
RWBoolean
isValid() const;
Returns TRUE if the file was successfully opened, FALSE otherwise.
RWBoolean
Read(char& c);
RWBoolean
Read(wchar_t& wc);
RWBoolean
Read(short& i);
RWBoolean
Read(int& i);
RWBoolean
Read(long& i);
RWBoolean
Read(unsigned char& c);
RWBoolean
Read(unsigned short& i);
RWBoolean
Read(unsigned int& i);
RWBoolean
Read(unsigned long& i);
RWBoolean
Read(float& f);
RWBoolean
Read(double& d);
Reads the indicated built-in type. Returns TRUE if the read is successful.
RWBoolean
Read(char* i,          size_t count);
RWBoolean
Read(wchar_t* i,       size_t count);
RWBoolean
Read(short* i,         size_t count);
RWBoolean
Read(int* i,           size_t count);
RWBoolean
Read(long* i,          size_t count);
RWBoolean
Read(unsigned char* i, size_t count);
RWBoolean
Read(unsigned short* i,size_t count);
RWBoolean
Read(unsigned int* i,  size_t count);
RWBoolean
Read(unsigned long* i, size_t count);
RWBoolean
Read(float* i,         size_t count);
RWBoolean
Read(double* i,        size_t count);
Reads count instances of the indicated built-in type into a block pointed to by i. Returns TRUE if the read is successful. Note that you are responsible for declaring i and for allocating the necessary storage before calling this function.
RWBoolean
Read(char* string);
Reads a character string, including the terminating null character, into a block pointed to by string. Returns TRUE if the read is successful. Note that you are responsible for declaring string and for allocating the necessary storage before calling this function. Beware of overflow when using this function.
RWBoolean
SeekTo(RWoffset offset)
Repositions the file pointer to offset bytes from the start of the file. Returns TRUE if the operation is successful.
RWBoolean
SeekToBegin();
Repositions the file pointer to the start of the file. Returns TRUE if the operation is successful.
RWBoolean
SeekToEnd();
Repositions the file pointer to the end of the file. Returns TRUE if the operation is successful.
RWBoolean
Write(char i);
RWBoolean
Write(wchar_t i);
RWBoolean
Write(short i);
RWBoolean
Write(int i);
RWBoolean
Write(long i);
RWBoolean
Write(unsigned char i);
RWBoolean
Write(unsigned short i);
RWBoolean
Write(unsigned int i);
RWBoolean
Write(unsigned long i);
RWBoolean
Write(float f);
RWBoolean
Write(double d);
Writes the appropriate built-in type. Returns TRUE if the write is successful.
RWBoolean
Write(const char* i,          size_t count);
RWBoolean
Write(const wchar_t* i,       size_t count);
RWBoolean
Write(const short* i,         size_t count);
RWBoolean
Write(const int* i,           size_t count);
RWBoolean
Write(const long* i,          size_t count);
RWBoolean
Write(const unsigned char* i, size_t count);
RWBoolean
Write(const unsigned short* i,size_t count);
RWBoolean
Write(const unsigned int* i,  size_t count);
RWBoolean
Write(const unsigned long* i, size_t count);
RWBoolean
Write(const float* i,         size_t count);
RWBoolean
Write(const double* i,        size_t count);
Writes count instances of the indicated built-in type from a block pointed to by i. Returns TRUE if the write is successful.
RWBoolean
Write(const char* string);
Writes a character string, including the terminating null character, from a block pointed to by string. Returns TRUE if the write is successful. Beware of non-terminated strings when using this function.

Static Public Member Functions

static RWBoolean
Exists(const char* filename, int mode = F_OK);
Returns TRUE if a file with name filename exists and may be accessed according to the mode specified. The mode may be ORed together from one or more of:
F_OK: "Exists" (Implied by any of the others)
X_OK: "Executable or searchable"
W_OK: "Writable"
R_OK: "Readable"
If your compiler or operating system does not support the POSIX access() function, then mode X_OK will always return FALSE.
RWFileManager

RWFileManager

RWFileManager . RWFile

Synopsis

typedef long     RWoffset ;
typedef unsigned long   RWspace;  // (typically)
#include <rw/filemgr.h>
RWFileManager f("file.dat");

Description

Class RWFileManager allocates and deallocates storage in a disk file, much like a "freestore" manager. It does this by maintaining a linked list of free space within the file.

Note - Class RWFileManager inherits class RWFile as a public base class; hence all the public member functions of RWFile are visible to RWFileManager. They are not listed here.

If a file is managed by an RWFileManager then reading or writing to unallocated space in the file will have undefined results. In particular, overwriting the end of allocated space is a common problem which usually results in corrupted data. One way to encounter this problem is to use binaryStoreSize() to discover the amount of space needed to store an RWCollection. For most purposes, the storage size of an RWCollection is found using the RWCollectable method recursiveStoreSize().

Persistence

None

Public Constructor

RWFileManager(const char* filename, const char* mode = 0);
Constructs an RWFileManager for the file with path name filename using mode mode. The mode is as given by the Standard C library function fopen(). If mode is zero (the default) then the constructor will attempt to open an existing file with the given filename for update (mode "rb+"). If this is not possible, then it will attempt to create a new file with the given filename (mode "wb+"). If the file exists and is not empty, then the constructor assumes it contains an existing file manager; other contents will cause an exception of type RWExternalErr to be thrown. If no file exists or if an existing file is empty, then the constructor will attempt to create the file (if necessary) and initialize it with a new file manager. The resultant object should be checked for validity using function isValid(). A possible exception that could occur is RWFileErr.

Public Member Functions

RWoffset
allocate(RWspace s);
Allocates s bytes of storage in the file. Returns the offset to the start of the storage location. The very first allocation for the file is considered "special" and can be returned at any later time by the function start(). A possible exception that could occur is RWFileErr.
void
deallocate(RWoffset t);
Deallocates (frees) the storage space starting at offset t. This space must have been previously allocated by a call to allocate(). The very first allocation ever made in the file is considered "special" and cannot be deallocated. A possible exception that could occur is RWFileErr.
RWoffset
endData();
Returns an offset just past the end of the file.
RWoffset
start();
Returns the offset of the first space ever allocated for data in this file. If no space has ever been allocated, returns RWNIL. This is typically used to "get started" and find the rest of the data in the file.
RWGBitVec(size)

RWGBitVec(size)

Synopsis

#include <rw/gbitvec.h>
declare(RWGBitVec,size)
RWGBitVec(size) a;

Description

RWGBitVec(size) is a bit vector of fixed length size. The length cannot be changed dynamically (see class RWBitVec if you need a bit vector whose length can be changed at run time). Objects of type RWGBitVec(size) are declared with macros defined in the standard C++ header file <generic.h>. Bits are numbered from 0 through size-1, inclusive.

Persistence

None

Example

In this example, a bit vector 24 bits long is declared and exercised:

  #include "rw/gbitvec.h"  
  #include <iostream.h>  
  const int VECSIZE = 8;  
  declare(RWGBitVec, VECSIZE)   // declare a 24 bit long vector  
  implement(RWGBitVec, VECSIZE) // implement the vector  
  main()  
  {  
    RWGBitVec(VECSIZE) a, b;   // Allocate two vectors.  
    a(2) = TRUE;               // Set bit 2 (the third bit) of a on.  
    b(3) = TRUE;               // Set bit 3 (the fourth bit) of b on.  
    RWGBitVec(VECSIZE) c = a ^ b;  // Set c to the XOR of a and b.  
    cout << "Vector 1" << "\t" << "Vector 2" << "\t"  
         << "Vector 1 xor Vector 2" << endl;  
    for(int i = 0; i < VECSIZE; i++)  
      cout << a[i] << "\t\t" << b[i] << "\t\t" << c[i] << endl;  
    return 0;  
  }  

Public Constructors

RWGBitVec(size)();
Construct a bit vector size elements long, with all bits initialized to FALSE.
RWGBitVec(size)(RWBoolean f);
Construct a bit vector size elements long, with all bits initialized to f.

Assignment Operators

RWGBitVec(sz)&
operator=(const RWGBitVec(sz)& v);
Set each element of self to the corresponding bit value of v. Return a reference to self.
RWGBitVec(sz)&
operator=(RWBoolean f);
Set all elements of self to the boolean value f.
RWGBitVec(sz)&
operator&=(const RWGBitVec(sz)& v);
RWGBitVec(sz)&
operator^=(const RWGBitVec(sz)& v);
RWGBitVec(sz)&
operator|=(const RWGBitVec(sz)& v);
Logical assignments. Set each element of self to the logical AND, XOR, or OR, respectively, of self and the corresponding bit in v.

Indexing Operators

RWBitRef
operator[](size_t i);
Returns a reference to the ith bit of self. This reference can be used as an lvalue. The index i must be between 0 and size-1, inclusive. Bounds checking will occur.
RWBitRef
operator()(size_t i);
Returns a reference to the ith bit of self. This reference can be used as an lvalue. The index i must be between 0 and size-1, inclusive. No bounds checking is done.

Public Member Functions

void
clearBit(size_t i);
Clears (i.e., sets to FALSE) the bit with index i. The index i must be between 0 and size-1. No bounds checking is performed. The following are equivalent, although clearBit(size_t) is slightly smaller and faster than using operator()(size_t):
      a(i) = FALSE;
      a.clearBit(i);
const RWByte*
data() const;
Returns a const pointer to the raw data of self. Should be used with care.
void
setBit(size_t i);
Sets (i.e., sets to TRUE) the bit with index i. The index i must be between 0 and size-1. No bounds checking is performed. The following are equivalent, although setBit(size_t) is slightly smaller and faster than using operator()(size_t):
      a(i) = TRUE;
      a.setBit(i);
RWBoolean
testBit(size_t i) const;
Tests the bit with index i. The index i must be between 0 and size-1. No bounds checking is performed. The following are equivalent, although testBit(size_t) is slightly smaller and faster than using
  operator()(size_t):
      if( a(i) ) doSomething();
      if( a.testBit(i) ) doSomething();

Related Global Functions

RWGBitVec(sz)
operator&(const RWGBitVec(sz)& v1, const RWGBitVec(sz)& v2);
RWGBitVec(sz)
operator^(const RWGBitVec(sz)& v1, const RWGBitVec(sz)& v2);
RWGBitVec(sz)
operator|(const RWGBitVec(sz)& v1, const RWGBitVec(sz)& v2);
Return the logical AND, XOR, and OR, respectively, of vectors v1 and v2.
RWBoolean
operator==(const RWGBitVec(sz)& v1, const RWGBitVec(sz)& v2)
           const;
Returns TRUE if each bit of v1 is set to the same value as the corresponding bit in v2. Otherwise, returns FALSE.
RWBoolean
operator!=(const RWGBitVec(sz)& v1, const RWGBitVec(sz)& v2)
           const;
Returns FALSE if each bit of v1 is set to the same value as the corresponding bit in v2. Otherwise, returns TRUE.
RWGDlist(type)

RWGDlist(type)

Synopsis

#include <rw/gdlist.h>
declare(RWGDlist, type)

RWGDlist(type) a;

Description

Class RWGDlist(type) represents a group of ordered elements of type type, not accessible by an external key. Duplicates are allowed. This class is implemented as a doubly-linked list. Objects of type RWGDlist(type) are declared with macros defined in the standard C++ header file <generic.h>. In order to find a particular item within the collection, a user-provided global "tester" function is required to test for a "match," definable in any consistent way. This function should have prototype:
RWBoolean yourTesterFunction(const type* c, const void* d);
The argument c is a candidate within the collection to be tested for a match. The argument d is for your convenience and will be passed to yourTesterFunction(). The function should return TRUE if a "match" is found between c and d.
In order to simplify the documentation below, an imaginary typedef
typedef RWBoolean (*yourTester)(const type*, const void*);
has been used for this tester function.

Persistence

None

Example


  #include <rw/gdlist.h>  
  #include <rw/rstream.h>  
  
  declare(RWGDlist,int)    /* Declare a list of ints */  
  
  main()  {  
    RWGDlist(int) list;    // Define a list of ints  
    int *ip;  
  
    list.insert(new int(5));   // Insert some ints  
    list.insert(new int(7));  
    list.insert(new int(1));  
    list.prepend(new int(11));  
  
    RWGDlistIterator(int) next(list);  
  
    while(ip = next() )  
      cout << *ip << endl;   // Print out the members  

  while(!list.isEmpty())  
      delete list.get();     // Remove & delete list items  
    return 0;  
  }  
  END FILE  

Program output:


       11  
       5  
       7  
       1  

Public Constructors

RWGDlist(type)();
Construct an empty collection.
RWGDlist(type)(type* a);
Construct a collection with one entry a.
RWGDlist(type)(const RWGDlist(type)& a);
Copy constructor. A shallow copy of a is made.

Assignment Operator

void
operator=(const RWGDlist(type)& a);
Assignment operator. A shallow copy of a is made.

Public Member Functions

type*
append(type* a);
Adds an item to the end of the collection. Returns nil if the insertion was unsuccessful.
void
apply(void (*ap)(type*, void*), void* );
Visits all the items in the collection in order, from first to last, calling the user-provided function pointed to by ap for each item. This function should have prototype:
   void yourApplyFunction(type* c, void*);
and can perform any operation on the object at address c. The last argument is useful for passing data to the apply function.
type*&
at(size_t i);
const type*
at(size_t i) const;
Returns a pointer to the ith item in the collection. The first variant can be used as an lvalue, the second cannot. The index i must be between zero and the number of items in the collection less one, or an exception of type TOOL_INDEX will be thrown.
void
clear();
Removes all items in the collection.
RWBoolean
contains(yourTester t, const void* d) const;
Returns TRUE if the collection contains an item for which the user-defined function pointed to by t finds a match with d.
RWBoolean
containsReference(const type* e) const;
Returns TRUE if the collection contains an item with the address e.
size_t
entries() const;
Returns the number of items in the collection.
type*
find(yourTester t, const void* d) const;
Returns the first item in the collection for which the user-provided function pointed to by t finds a match with d, or nil if no item is found.
type*
findReference(const type* e) const;
Returns the first item in the collection with the address e, or nil if no item is found.
type*
first() const;
Returns the first item of the collection.
type*
get();
Returns and removes the first item of the collection.
type*
insert(type* e);
Adds an item to the end of the collection and returns it. Returns nil if the insertion was unsuccessful.
void
insertAt(size_t indx, type* e);
Adds a new item to the collection at position indx. The item previously at position i is moved to i+1, etc. The index indx must be between 0 and the number of items in the collection, or an exception of type TOOL_INDEX will be thrown.
RWBoolean
isEmpty() const;
Returns TRUE if the collection is empty, otherwise FALSE.
type*
last() const;
Returns the last item of the collection.
size_t
occurrencesOf(yourTester t, const void* d) const;
Returns the number of occurrences in the collection for which the user-provided function pointed to by t finds a match with d.
size_t
occurrencesOfReference(const type* e) const;
Returns the number of items in the collection with the address e.
type*
prepend(type* a);
Adds an item to the beginning of the collection. Returns nil if the insertion was unsuccessful.
type*
remove(yourTester t, const void* d);
Removes and returns the first item from the collection for which the user-provided function pointed to by t finds a match with d, or returns nil if no item is found.
type*
removeReference(const type* e);
Removes and returns the first item from the collection with the address e, or returns nil if no item is found.
RWGDlistIterator(type)

RWGDlistIterator(type)

Synopsis

#include <rw/gdlist.h>
declare(RWGDlist, type)
RWGDlist(type) a;
RWGDlistIterator(type) I(a) ;

Description

Iterator for class RWGDlist(type), which allows sequential access to all the elements of a doubly-linked list. Elements are accessed in order, in either direction. As with all Rogue Wave iterators, the "current item" is undefined immediately after construction -- you must define it by using operator() or some other (valid) operation.
Once the iterator has advanced beyond the end of the collection it is no longer valid -- continuing to use it will bring undefined results.
In order to simplify the documentation below, an imaginary typedef
typedef RWBoolean (*yourTester)(const type*, const void*);
has been used. See the documentation for class RWGDlist(type) for an explanation of this function.

Persistence

None

Example

See class RWGDlist(type)

Public Constructor

RWGDlistIterator(type)( RWGDlist(type)& list);
Construct an iterator for the RWGDlist(type) list. Immediately after construction, the position of the iterator is undefined.

Public Member Operators

type*
operator()();
Advances the iterator to the next item and returns it. Returns nil if at the end of the collection.
void
operator++();
Advances the iterator one item.
void
operator--();
Moves the iterator back one item.
void
operator+=(size_t n);
Advances the iterator n items.
void
operator-=(size_t n);
Moves the iterator back n items.

Public Member Functions

RWBoolean
atFirst() const;
Returns TRUE if the iterator is at the start of the list, FALSE otherwise;
RWBoolean
atLast() const;
Returns TRUE if the iterator is at the end of the list, FALSE otherwise;
type*
findNext(yourTester t,const type* d);
Moves the iterator to the next item for which the function pointed to by t finds a match with d and returns it. Returns nil if no match is found, in which case the position of the iterator will be undefined.
type*
findNextReference(const type* e);
Moves the iterator to the next item with the address e and returns it. Returns nil if no match is found, in which case the position of the iterator will be undefined.
type*
insertAfterPoint(type* a);
Adds item a after the current iterator position and return the item. The position of the iterator is left unchanged.
type*
key() const;
Returns the item at the current iterator position.
type*
remove();
Removes and returns the item at the current cursor position. Afterwards, the iterator will be positioned at the previous item in the list.
type*
removeNext(yourTester t, const type* d);
Moves the iterator to the next item for which the function pointed to by t finds a "match" with d and removes and returns it. Returns nil if no match is found, in which case the position of the iterator will be undefined.
type*
removeNextReference(const type* a);
Moves the iterator to the next item with the address e and removes and returns it. Returns nil if no match is found, in which case the position of the iterator will be undefined.
void
reset();
Resets the iterator to its initial state.
void
toFirst();
Moves the iterator to the first item in the list.
void
toLast();
Moves the iterator to the last item in the list.
RWGOrderedVector(val)

RWGOrderedVector(val)

Synopsis

#include <rw/gordvec.h>
declare(RWGVector,val)
declare(RWGOrderedVector,val)
implement(RWGVector,val)
implement(RWGOrderedVector,val)

RWGOrderedVector(val) v;// Ordered vector of objects of val val.

Description

Class RWGOrderedVector(val) represents an ordered collection of objects of val val. Objects are ordered by the order of insertion and are accessible by index. Duplicates are allowed. RWGOrderedVector(val) is implemented as a vector, using macros defined in the standard C++ header file <generic.h>. Note that it is a value-based collection: items are copied in and out of the collection.
The class val must have:
  • a default constructor;
  • well-defined copy semantics (val::val(const val&) or equiv.);
  • well-defined assignment semantics (val::operator=(const val&) or equiv.);
  • well-defined equality semantics (val::operator==(const val&) or equiv.).
To use this class you must declare and implement its base class as well as the class itself. For example, here is how you declare and implement an ordered collection of doubles:
declare(RWGVector,double)                     // Declare base class
declare(RWGOrderedVector,double)  // Declare ordered vector

// In one and only one .cpp file you must put the following:
implement(RWGVector,double)            // Implement base class
implement(RWGOrderedVector,double)     // Implement ordered vector
For each val of RWGOrderedVector you must include one (and only one) call to the macro implement somewhere in your code for both the RWGOrderedVector itself and for its base class RWGVector.

Persistence

None

Example

Here's an example that uses an ordered vector of RWCStrings.

  #include <rw/gordvec.h>  
  #include <rw/cstring.h>  
  #include <rw/rstream.h>  
  
  declare(RWGVector,RWCString)  
  declare(RWGOrderedVector,RWCString)  
  implement(RWGVector,RWCString)  
  implement(RWGOrderedVector,RWCString)  
  
  main()  {  
    RWGOrderedVector(RWCString) vec;  
  
    RWCString one("First");  
    vec.insert(one);  
  
    vec.insert("Second");   // Automatic val conversion occurs  
    vec.insert("Last");     // Automatic val conversion occurs  
  
    for(size_t i=0; i<vec.entries(); i++)  cout << vec[i] << endl;  
  
    return 0;  
  }  

Program output:


  First  
  Second  
  Last  

Public Constructors

RWGOrderedVector(val)(size_t capac=RWDEFAULT_CAPACITY);
Construct an ordered vector of elements of val val. The initial capacity of the vector will be capac whose default value is RWDEFAULT_CAPACITY. The capacity will be automatically increased as necessary should too many items be inserted, a relatively expensive process because each item must be copied into the new storage.

Public Member Functions

val
operator()(size_t i) const;
val&
operator()(size_t i);
Return the ith value in the vector. The index i must be between 0 and one less than the number of items in the vector. No bounds checking is performed. The second variant can be used as an lvalue, the first cannot.
val
operator[](size_t i) const;
val&
operator[](size_t i);
Return the ith value in the vector. The index i must be between 0 and one less than the number of items in the vector. Bounds checking will be performed. The second variant can be used as an lvalue, the first cannot.
void
clear();
Remove all items from the collection.
const val*
data() const;
Returns a pointer to the raw data of self. Should be used with care.
size_t
entries() const;
Return the number of items currently in the collection.
size_t
index(val item) const;
Perform a linear search of the collection returning the index of the first item that isEqual to the argument item. If no item is found, then it returns RW_NPOS.
void
insert(val item);
Add the new value item to the end of the collection.
void
insertAt(size_t indx, val item);
Add the new value item to the collection at position indx. The value of indx must be between zero and the length of the collection. No bounds checking is performed. Old items from index indx upwards will be shifted to higher indices.
RWBoolean
isEmpty() const;
Returns TRUE if the collection has no entries. FALSE otherwise.
void
size_t
length() const;
Synonym for entries().
val
pop();
Removes and returns the last item in the vector.
void
push(val);
Synonym for insert().
removeAt(size_t indx);
Removes the item at position indx from the collection. The value of indx must be between zero and one less than the length of the collection. No bounds checking is performed. Old items from index indx+1 will be shifted to lower indices. E.g., the item at index indx+1 will be moved to position indx, etc.
void
resize(size_t newCapacity);
Change the capacity of the collection to newCapacity, which must be at least as large as the present number of items in the collection. Note that the actual number of items in the collection does not change, just the capacity.
RWGQueue(type)

RWGQueue(type)

Synopsis

#include <rw/gqueue.h>
declare(RWGQueue, type)

RWGQueue(type) a ;

Description

Class RWGQueue(type) represents a group of ordered elements, not accessible by an external key. A RWGQueue(type) is a first in, first out (FIFO) sequential list for which insertions are made at one end (the "tail"), but all removals are made at the other (the "head"). Hence, the ordering is determined externally by the ordering of the insertions. Duplicates are allowed. This class is implemented as a singly-linked list. Objects of type RWGQueue(type) are declared with macros defined in the standard C++ header file <generic.h>. In order to find a particular item within the collection, a user-provided global "tester" function is required to test for a "match", definable in any consistent way. This function should have prototype:
RWBoolean yourTesterFunction(const type* c, const void* d);
The argument c is a candidate within the collection to be tested for a match. The argument d is for your convenience and will be passed to yourTesterFunction(). The function should return TRUE if a "match" is found between c and d.
In order to simplify the documentation below, an imaginary typedef
typedef RWBoolean (*yourTester)(const type*, const void*);
has been used for this tester function.

Persistence

None

Public Constructors

RWGQueue(type)();
Construct an empty queue.
RWGQueue(type)(type* a);
Construct a queue with one entry a.
RWGQueue(type)(const RWGQueue(type)& q);
Copy constructor. A shallow copy of q is made.

Assignment Operator

void
operator=(const RWGQueue(type)& q);
Assignment operator. A shallow copy of q is made.

Public Member Functions

type*
append(type* a);
Adds a to the end of the queue and returns it. Returns nil if the insertion was unsuccessful.
void
clear();
Removes all items from the queue.
RWBoolean
contains(yourTester t, const void* d) const;
Returns TRUE if the queue contains an item for which the user-defined function pointed to by t finds a match with d.
RWBoolean
containsReference(const type* e) const;
Returns TRUE if the queue contains an item with the address e.
size_t
entries() const;
Returns the number of items in the queue.
type*
first() const;
Returns the first item in the queue, or nil if the queue is empty.
type*
get();
Returns and removes the first item in the queue. Returns nil if the queue is empty.
RWBoolean
isEmpty() const;
Returns TRUE if the queue is empty, otherwise FALSE.
type*
insert(type* a);
Calls append(type*) with a as the argument.
type*
last();
Returns the last (most recently inserted) item in the queue, or nil if the queue is empty.
size_t
occurrencesOf(yourTester t, const void* d) const;
Returns the number of items in the queue for which the user-provided function pointed to by t finds a match with d.
size_t
occurrencesOfReference(const type* e) const;
Returns the number of items in the queue with the address e.
RWGSlist(type)

RWGSlist(type)

Synopsis

#include <rw/gslist.h>
declare(RWGSlist, type)

RWGSlist(type) a ;

Description

Class RWGSlist(type) represents a group of ordered elements of type type, not accessible by an external key. Duplicates are allowed. This class is implemented as a singly-linked list. Objects of type RWGSlist(type) are declared with macros defined in the standard C++ header file <generic.h>. In order to find a particular item within the collection, a user-provided global "tester" function is required to test for a "match," definable in any consistent way. This function should have prototype:
RWBoolean yourTesterFunction(const type* c, const void* d);
The argument c is a candidate within the collection to be tested for a match. The argument d is for your convenience and will be passed to yourTesterFunction(). The function should return TRUE if a "match" is found between c and d.
In order to simplify the documentation below, an imaginary typedef
typedef RWBoolean (*yourTester)(const type*, const void*);
has been used for this tester function.

Persistence

None

Public Constructors

RWGSlist(type)();
Construct an empty collection.
RWGSlist(type)(type* a);
Construct a collection with one entry a.
RWGSlist(type)(const RWGSlist(type)& a);
Copy constructor. A shallow copy of a is made.

Assignment Operator

void
operator=(const RWGSlist(type)&);
Assignment operator. A shallow copy of a is made.

Public Member Functions

type*
append(type* a);
Adds an item to the end of the collection and returns it. Returns nil if the insertion was unsuccessful.
void
apply(void (*ap)(type*, void*), void* );
Visits all the items in the collection in order, from first to last, calling the user-provided function pointed to by ap for each item. This function should have prototype:
void yourApplyFunction(type* c, void*);
and can perform any operation on the object at address c. The last argument is useful for passing data to the apply function.
type*&
at(size_t i);
const type*
at(size_t i) const;
Returns a pointer to the ith item in the collection. The first variant can be used as an lvalue, the second cannot. The index i must be between zero and the number of items in the collection less one, or an exception of type TOOL_INDEX will be thrown.
void
clear();
Removes all items in the collection.
RWBoolean
contains(yourTester t, const void* d) const;
Returns TRUE if the collection contains an item for which the user-defined function pointed to by t finds a match with d.
RWBoolean
containsReference(const type* e) const;
Returns TRUE if the collection contains an item with the address e.
size_t
entries() const;
Returns the number of items in the collection.
type*
find(yourTester t, const void* d) const;
Returns the first item in the collection for which the user-provided function pointed to by t finds a match with d, or nil if no item is found.
type*
findReference(const type* e) const;
Returns the first item in the collection with the address e, or nil if no item is found.
type*
first() const;
Returns the first item of the collection.
type*
get();
Returns and removes the first item of the collection.
type*
insert(type* e);
Adds an item to the end of the collection and returns it. Returns nil if the insertion was unsuccessful.
void
insertAt(size_t indx, type* e);
Adds a new item to the collection at position indx. The item previously at position i is moved to i+1, etc. The index indx must be between 0 and the number of items in the collection, or an exception of type TOOL_INDEX will be thrown.
RWBoolean
isEmpty() const;
Returns TRUE if the collection is empty, otherwise FALSE.
type*
last() const;
Returns the last item of the collection.
size_t
occurrencesOf(yourTester t, const void* d) const;
Returns the number of occurrences in the collection for which the user-provided function pointed to by t finds a match with d.
size_t
occurrencesOfReference(const type* e) const;
Returns the number of items in the collection with the address e.
type*
prepend(const type* a);
Adds an item to the beginning of the collection and returns it. Returns nil if the insertion was unsuccessful.
type*
remove(yourTester t, const void* d);
Removes and returns the first item from the collection for which the user-provided function pointed to by t finds a match with d, or returns nil if no item is found.
type*
removeReference(const type* e);
Removes and returns the first item from the collection with the address e, or returns nil if no item is found.
RWGSlistIterator(type)

RWGSlistIterator(type)

Synopsis

#include <rw/gslist.h>
declare(RWGSlist, type)

RWGSlist(type) a ;
RWGSlistIterator(type) I(a);

Description

Iterator for class RWGSlist(type), which allows sequential access to all the elements of a singly-linked list. Elements are accessed in order, first to last.
As with all Rogue Wave iterators, the "current item" is undefined immediately after construction -- you must define it by using operator() or some other (valid) operation.
Once the iterator has advanced beyond the end of the collection it is no longer valid -- continuing to use it will bring undefined results.
In order to simplify the documentation below, an imaginary typedef
typedef RWBoolean (*yourTester)(const type*, const void*);
has been used. See the documentation for class RWGSlist(type) for an explanation of this function.

Persistence

None

Public Constructor

RWGSlistIterator(type)( RWGSlist(type)& list);
Constructs an iterator for the RWGSlist(type) list. Immediately after construction, the position of the iterator is undefined.

Public Member Operators

type*
operator()();
Advances the iterator to the next item and returns it. Returns nil if it is at the end of the collection.
void
operator++();
Advances the iterator one item.
void
operator+=(size_t n);
Advances the iterator n items.

Public Member Functions

RWBoolean
atFirst() const;
Returns TRUE if the iterator is at the start of the list, FALSE otherwise;
RWBoolean
atLast() const;
Returns TRUE if the iterator is at the end of the list, FALSE otherwise;
type*
findNext(yourTester t,const type* d);
Moves the iterator to the next item for which the function pointed to by t finds a match with d and returns it. Returns nil if no match is found, in which case the position of the iterator will be undefined.
type*
findNextReference(const type* e);
Moves the iterator to the next item with the address e and returns it. Returns nil if no match is found, in which case the position of the iterator will be undefined.
type*
insertAfterPoint(type* a);
Adds item a after the current iterator position and return the item. The position of the iterator is left unchanged.
type*
key() const;
Returns the item at the current iterator position.
type*
remove();
Removes and returns the item at the current cursor position. Afterwards, the iterator will be positioned at the previous item in the list. In a singly-linked list, this function is an inefficient operation because the entire list must be traversed, looking for the link before the link to be removed.
type*
removeNext(yourTester t, const type* d);
Moves the iterator to the next item for which the function pointed to by t finds a "match" with d and removes and returns it. Returns nil if no match is found, in which case the position of the iterator will be undefined.
type*
removeNextReference(const type* e);
Moves the iterator to the next item with the address e and removes and returns it. Returns nil if no match is found, in which case the position of the iterator will be undefined.
void
reset();
Resets the iterator to its initial state.
void
toFirst();
Moves the iterator to the start of the list.
void
toLast();
Moves the iterator to the end of the list.
RWGSortedVector(val)

RWGSortedVector(val)

RWGSortedVector(val) . RWGVector(val)

Synopsis

#include <rw/gsortvec.h>
declare(RWGSortedVector,val)
implement(RWGSortedVector, val)
RWGSortedVector(val) v;    // A sorted vector of vals .

Description

Class RWGSortedVector(val) represents a vector of elements of val val, sorted using an insertion sort. The elements can be retrieved using an index or a search. Duplicates are allowed. Objects of val RWGSortedVector(val) are declared with macros defined in the standard C++ header file <generic.h>. Note that it is a value-based collection: items are copied in and out of the collection.
The class val must have:
  • a default constructor;
  • well-defined copy semantics (val::val(const val&) or equiv.);
  • well-defined assignment semantics (val::operator=(const val&) or equiv.);
  • well-defined equality semantics (val::operator==(const val&) or equiv.);
  • well-defined less-than semantics (val::operator<(const val&) or equiv.)..
To use this class you must declare and implement its base class as well as the class itself. For example, here is how you declare and implement a sorted collection of doubles:
declare(RWGVector,double)             // Declare base class
declare(RWGSortedVector,double)     // Declare sorted vector

// In one and only one .cpp file you must put the following:
implement(RWGVector,double)         // Implement base class
implement(RWGSortedVector,double)   // Implement sorted vector
For each val of RWGSortedVector you must include one (and only one) call to the macro implement somewhere in your code for both the RWGSortedVector itself and for its base class RWGVector.
Insertions and retrievals are done using a binary search. Note that the constructor of an RWGSortedVector(val) requires a pointer to a "comparison function." This function should have protoval:
int comparisonFunction(const val* a, const val* b);
and should return an int less than, greater than, or equal to zero, depending on whether the item pointed to by a is less than, greater than, or equal to the item pointed to by b. Candidates from the collection will appear as a, the key as b.

Persistence

None

Example

Here's an example of a sorted vector of ints:

  #include <rw/gsortvec.h>  
  #include <rw/rstream.h>  
  
  declare(RWGVector,int)  
  declare(RWGSortedVector,int)  
  implement(RWGVector,int)  
  implement(RWGSortedVector,int)  
  
  // Declare and define the "comparison function":  
  int compFun(const int* a, const int* b)  {  
    return *a - *b;  
  }  
  
  main()  {  
    // Declare and define an instance,  
    // using the comparison function 'compFun':  
    RWGSortedVector(int) avec(compFun);  
    // Do some insertions:  
    avec.insert(3);          // 3  
    avec.insert(17);         // 3 17  
    avec.insert(5);          // 3  5 17  
  
    cout << avec(1);         // Prints '5'  
    cout << avec.index(17);  // Prints '2'  
  }  
  END FILE  

Public Constructors

RWGSortedVector(val)( int (*f)(const val*, const val*) );
Construct a sorted vector of elements of val val, using the comparison function pointed to by f. The initial capacity of the vector will be set by the value RWDEFAULT_CAPACITY. The capacity will automatically be increased should too many items be inserted.
RWGSortedVector(val)(int (*f)(const val*, const val*),
                size_t N);
Construct a sorted vector of elements of val val, using the comparison function pointed to by f. The initial capacity of the vector will be N. The capacity will automatically be increased should too many items be inserted.

Public Member Functions

val
operator()(size_t i) const;
Return the ith value in the vector. The index i must be between 0 and the length of the vector less one. No bounds checking is performed.
val
operator[](size_t i) const;
Return the ith value in the vector. The index i must be between 0 and the length of the vector less one. Bounds checking is performed.
size_t
entries() const;
Returns the number of items currently in the collection.
size_t
index(val v);
Return the index of the item with value v. The value "RW_NPOS" is returned if the value does not occur in the vector. A binary search, using the comparison function, is done to find the value. If duplicates are present, the index of the first instance is returned.
RWBoolean
insert(val v);
Insert the new value v into the vector. A binary search, using the comparison function, is performed to determine where to insert the value. The item will be inserted after any duplicates. If the insertion causes the vector to exceed its capacity, it will automatically be resized by an amount given by RWDEFAULT_RESIZE.
void
removeAt(size_t indx);
Remove the item at position indx from the collection. The value of indx must be between zero and the length of the collection less one. No bounds checking is performed. Old items from index indx+1 will be shifted to lower indices. E.g., the item at index indx+1 will be moved to position indx, etc.
void
resize(size_t newCapacity);
Change the capacity of the collection to newCapacity, which must be at least as large as the present number of items in the collection. Note that the actual number of items in the collection does not change, just the capacity.
RWGStack(type)

RWGStack(type)

Synopsis

#include <rw/gstack.h>
declare(RWGStack,type)

RWGStack(type) a ;

Description

Class RWGStack(type) represents a group of ordered elements, not accessible by an external key. A RWGStack(type) is a last in, first out (LIFO) sequential list for which insertions and removals are made at the beginning of the list. Hence, the ordering is determined externally by the ordering of the insertions. Duplicates are allowed. This class is implemented as a singly-linked list. Objects of type RWGStack(type) are declared with macros defined in the standard C++ header file <generic.h>. In order to find a particular item within the collection, a user-provided global "tester" function is required to test for a "match," definable in any consistent way. This function should have prototype:
RWBoolean yourTesterFunction(const type* c, const void* d);
The argument c is a candidate within the collection to be tested for a match. The argument d is for your convenience and will be passed to yourTesterFunction(). The function should return TRUE if a "match" is found between c and d.
In order to simplify the documentation below, an imaginary typedef
typedef RWBoolean (*yourTester)(const type*, const void*);
has been used for this tester function.

Persistence

None

Public Constructors

RWGStack(type)();
Constructs an empty stack.
RWGStack(type)(type* a);
Constructs a stack with one entry a.
RWGStack(type)(const RWGStack(type)& a);
Copy constructor. A shallow copy of a is made.

Assignment Operator

void
operator=(const RWGStack(type)& a);
Assignment operator. A shallow copy of a is made.

Public Member Functions

void
clear();
Removes all items from the stack.
RWBoolean
contains(yourTester t, const void* d) const;
Returns TRUE if the stack contains an item for which the user-defined function pointed to by t finds a match with d.
RWBoolean
containsReference(const type* e) const;
Returns TRUE if the stack contains an item with the address e.
size_t
entries() const;
Returns the number of items in the stack.
RWBoolean
isEmpty() const;
Returns TRUE if the stack is empty, otherwise FALSE.
size_t
occurrencesOf(yourTester t, const void* d) const;
Returns the number of items in the stack for which the user-provided function pointed to by t finds a match with d.
size_t
occurrencesOfReference(const type* e) const;
Returns the number of items in the stack with the address e.
type*
pop();
Removes and returns the item at the top of the stack, or returns nil if the stack is empty.
void
push(type* a);
Adds an item to the top of the stack.
type*
top() const;
Returns the item at the top of the stack or nil if the stack is empty.
RWGVector(val)

RWGVector(val)

Synopsis

#include <rw/gvector.h>
declare(RWGVector,val)
implement(RWGVector,val)

RWGVector(val) a;   // A Vector of val's.

Description

Class RWGVector(val) represents a group of ordered elements, accessible by an index. Duplicates are allowed. This class is implemented as an array. Objects of type RWGVector(val) are declared with macros defined in the standard C++ header file <generic.h>. Note that it is a value-based collection: items are copied in and out of the collection.
The class val must have:
  • a default constructor;
  • well-defined copy semantics (val::val(const val&) or equiv.);
  • well-defined assignment semantics (val::operator=(const val&) or equivalent).
For each type of RWGVector, you must include one (and only one) call to the macro implement, somewhere in your code.

Persistence

None

Example


  #include <rw/gvector.h>  
  #include <rw/rwdate.h>  
  #include <rw/rstream.h>  
  
  declare(RWGVector, RWDate)   /* Declare a vector of dates */  
  implement(RWGVector, RWDate) /* Implement a vector of dates */  
  
  main()  {  
    RWGVector(RWDate) oneWeek(7);  
    for (int i=1; i<7; i++)  
      oneWeek(i) = oneWeek(0) + i;  
  
    for (i=0; i<7; i++)  
      cout << oneWeek(i) << endl;  
  
    return 0;  
  }  

Program output:


  04/12/93  
  04/13/93  
  04/14/93  
  04/15/93  
  04/16/93  
  04/17/93  
  04/18/93  

Public Constructors

RWGVector(val)();
Construct an empty vector.
RWGVector(val)(size_t n);
Construct a vector with length n. The initial values of the elements can (and probably will) be garbage.
RWGVector(val)(size_t n, val v);
Construct a vector with length n. Each element is assigned the value v.
RWGVector(val)(RWGVector(val)& s);
Copy constructor. The entire vector is copied, including all embedded values.

Public Member Operators

RWGVector(val)&
operator=(RWGVector(val)& s);
Assignment operator. The entire vector is copied.
RWGVector(val)&
operator=(val v);
Sets all elements of self to the value v.
val
operator()(size_t i) const;
val&
operator()(size_t i);
Return the i'th element in the vector. The index i must be between zero and the length of the vector less one. No bounds checking is performed. The second variant can be used as an lvalue.
val
operator[](size_t i) const;
val&
operator[](size_t i);
Return the ith element in the vector. The index i must be between zero and the length of the vector less one. Bounds checking is performed.

Public Member Functions

const val*
data() const;
Returns a pointer to the raw data of self. Should be used with care.
size_t
length() const;
Returns the length of the vector.
void
reshape(size_t n);
Resize the vector. If the vector shrinks, it will be truncated. If the vector grows, then the value of the additional elements will be undefined.
RWHashDictionary

RWHashDictionary

RWHashDictionary . RWSet . RWHashTable . RWCollection . RWCollectable

Synopsis

typedef RWHashDictionary Dictionary;  // Smalltalk typedef.
#include <rw/hashdict.h>
RWHashDictionary  a ;

Description

An RWHashDictionary represents a group of unordered values, accessible by external keys. Duplicate keys are not allowed. RWHashDictionary is implemented as a hash table of associations of keys and values. Both the key and the value must inherit from the abstract base class RWCollectable, with a suitable definition of the virtual function hash() and isEqual() for the key.
This class corresponds to the Smalltalk class Dictionary.

Persistence

None

Public Constructors

RWHashDictionary(size_t n = RWDEFAULT_CAPACITY);
Construct an empty hashed dictionary using n hashing buckets.
RWHashDictionary(const RWHashDictionary& hd);
Copy constructor. A shallow copy of the collection hd is made.

Public Member Operators

void
operator=(const RWHashDictionary& hd);
Assignment operator. A shallow copy of the collection hd is made.
RWBoolean
operator<=(const RWHashDictionary& hd) const;
Returns TRUE if for every key-value pair in self, there is a corresponding key in hd that isEqual. Their corresponding values must also be equal.

Note - If you inherit from RWHashDictionary 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 RWHashDictionary& hd) const;
Returns TRUE if self and hd have the same number of entries and if for every key-value pair in self, there is a corresponding key in hd that isEqual. Their corresponding values must also be equal.

Public Member Functions

void
applyToKeyAndValue(RWapplyKeyAndValue ap, void* x);
Applies the user-supplied function pointed to by ap to each key-value pair of the collection. Items are not visited in any particular order. An untyped argument may be passed to the ap function through x.
RWBinaryTree
asBinaryTree();
RWBag
asBag() const;
RWSet
asOrderedCollection() const;
asSet() const;
RWOrdered
RWBinaryTree
asSortedCollection() const;
Converts the RWHashDictionary 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 in the collection.
virtual void
clearAndDestroy();
Redefined from class RWCollection. Removes all key-value pairs in the collection, and deletes 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;
Inherited from class RWSet.
virtual RWCollectable*
find(const RWCollectable* target) const;
Redefined from class RWCollection. Returns the key which isEqual to the object pointed to by target, or nil if no key was found.
RWCollectable*
findKeyAndValue(const RWCollectable* target,
     RWCollectable*& v) const;
Returns the key which isEqual to the item 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 isEqual to the item 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 isEqual to the item 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.
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 __RWHASHDICTIONARY.
virtual RWBoolean
isEmpty() const;
Inherited from class RWSet.
virtual RWBoolean
isEqual(const RWCollectable* a) const;
Inherited from class RWCollectable.
virtual size_t
occurrencesOf(const RWCollectable* target) const;
Inherited from class RWSet. Returns the number of keys which isEqual to the item pointed to by 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 where the key isEqual to the item 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 where the key isEqual to the item 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 where the key isEqual to the item pointed to by target. Returns the key, or nil if no match was found. The value part of the removed pair is put in v. You are responsible for defining v before calling this function.
void
resize(size_t n = 0);
Inherited from class RWSet.
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 RWHashDictionary. It inserts keys and values for which the function returns TRUE into a new RWHashDictionary 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 a virtual function which hides the non-virtual function inherited from RWCollection.
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 RWHashDictionary. It inserts keys and values for which the function returns TRUE into a new RWHashDictionary 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 a virtual function which hides the non-virtual function inherited from RWCollection.
RWStringID
stringID();
(acts virtual) Inherited from class RWCollectable.
RWHashDictionaryIterator

RWHashDictionaryIterator

RWHashDictionaryIterator . RWIterator

Synopsis

#include <rw/hashdict.h>

RWHashDictionary hd;
RWHashDictionaryIterator  iter(hd);

Description

Iterator for class RWHashDictionary, allowing sequential access to all the elements of RWHashDictionary. Since RWHashDictionary is unordered, elements are not accessed in any particular order.
Like all Rogue Wave iterators, the "current item" is undefined immediately after construction -- you must define it by using operator() or some other (valid) operation.
Once the iterator has advanced beyond the end of the collection it is no longer valid -- continuing to use it will bring undefined results.

Persistence

None

Public Constructor

RWHashDictionaryIterator(RWHashDictionary&);
Construct an iterator for an RWHashDictionary collection. Immediately after construction, the position of the iterator is undefined until positioned.

Public Member Operator

virtual RWCollectable*
operator()();
Redefined from class RWIterator. Advances the iterator to the next key-value pair and returns the key. Returns nil if the cursor is at the end of the collection. Use member function value() to recover the value.

Public Member Functions

virtual RWCollectable*
findNext(const RWCollectable* target);
Redefined from class RWIterator. Moves the iterator to the next key-value pair where the key isEqual to the object pointed to by target. Returns the key or nil if no key was found.
virtual RWCollectable*
key() const;
Redefined from class RWIterator. Returns the key at the current iterator position.
RWCollectable*
remove();
Removes the key-value pair at the current iterator position. Returns the key, or nil if there was no key-value pair.
RWCollectable*
removeNext(const RWCollectable* target);
Moves the iterator to the next key-value pair where the key isEqual to the object pointed to by target. Removes the key-value pair, returning the key or nil if there was no match.
virtual void
reset();
Redefined from class RWIterator. Inherited from class RWSetIterator. Resets the iterator to its initial state.
RWCollectable*
value() const;
Returns the value at the current iterator position.
RWCollectable*
value(RWCollectable* newValue) const;
Replaces the value at the current iterator position and returns the old value.
rw_hashmap

rw_hashmap

Synopsis

#include <rw/rwstl/hashmap.h>
rw_hashmap<K,V,Hash,EQ> map;

Description

Class rw_hashmap<K,V,Hash,EQ> maintains a collection of mappings between K and V, implemented as a hash table of pair<const K,V> . Pairs with duplicate keys are not allowed. Two pairs having duplicate keys is the result of the EQ comparison, applied to the first element of each, is TRUE. Since this is a value based collection, objects are copied into and out of the collection. As with all classes that meet the ANSI associative container specification, rw_hashmap provides for iterators that reference its elements. Operations that alter the contents of rw_hashmap may invalidate other iterators that reference the container. Since the contents of rw_hashmap are in pseudo-random order, the only iterator ranges that will usually make sense are the results of calling equal_range(key), and the entire range from begin() to end().

Persistence

None

Public Typedefs

typedef K                  key_type;
typedef Hash               key_hash;
typedef EQ                 key_equal;
typedef pair<K,V>          value_type; // or ... "const K"
typedef (unsigned)         size_type; //from rw_slist
typedef (int)              difference_type; // from rw_slist
typedef (value_type&)      reference;
typedef (const value_type&) const_reference; //from rw_slist
Iterators over rw_hashmap<K,V,Hash,EQ> are forward iterators.
typedef (scoped Iterator)      iterator;
typedef (scoped ConstIterator)  const_iterator;

Public Constructors

rw_hashmap<K,V,Hash,EQ>(size_type sz = 1024,
                        const Hash& h = Hash(),
                        const EQ& eq = EQ());
Construct an empty rw_hashmap<K,V,Hash,EQ> with sz slots, using h as the hash object, and eq as the equality comparator.
rw_hashmap<K,V,Hash,EQ>(const rw_hashmap<K,V,Hash,EQ>& map);
Construct an rw_hashmap<K,V,Hash,EQ> which is a copy of map. Each element from map will be copied into self.
rw_hashmap<K,V,Hash,EQ>(const_iterator first,
                        const_iterator bound
                        size_type sz=1024,