Languages Library Tools.h++ Manual Abstract Part Number Edition Published Product Version Release ID Supported Releases This manual describes the Tools.h++ Class Library which is a set of collection classes that are intended for use by C++ programmers. 104011 First February 1994 Version 6 D20.01 This manual supports D20.01 and all subsequent releases until otherwise indicated in a new edition.
Document History Edition Part Number Product Version First 104011 Version 6 Earliest Supported Release D20.01 Published February 1994 New editions incorporate any updates issued since the previous edition. A plus sign (+) after a release ID indicates that this manual describes function added to the base release, either by an interim product modification (IPM) or by a new product version on a .99 site update tape (SUT).
Contents 1. Introduction 1-1 Overview and features 1-1 Supported C++ compilers 1-3 Philosophy 1-3 Conventions 1-4 Reading this manual 1-5 2. Compiling Programs 2-1 Porting considerations 2-1 3.
Common member functions 3-4 Persistence 3-4 Store size 3-5 Stream I/O 3-5 Comparisons 3-6 Memory allocation 3-6 Information flow 3-7 Multi-thread safe 3-7 Eight-bit clean 3-8 Embedded nulls 3-8 Indexing 3-8 Version 3-8 Public Class Hierarchy 3-9 4. Internationalization 4-1 RWLocale and RWZone 4-3 Dates 4-4 Time 4-6 Numbers 4-9 Currency 4-10 Wrap up 4-11 5.
Pattern matching 5-5 Regular expressions 5-5 String I/O 5-6 iostreams 5-6 Virtual streams 5-8 Tokenizer 5-8 Multibyte strings 5-9 Wide character strings 5-10 6. Using Class RWDate 6-1 Example 6-2 Constructors 6-2 7. Using Class RWTime 7-1 Setting the time zone 7-1 Constructors 7-2 Member functions 7-2 8. Virtual Streams 8-1 Specializing virtual streams 8-4 Simple example 8-5 Recap 8-7 9. Using Class RWFile 9-1 Example 9-2 10.
11. Using Class RWBTreeOnDisk 11-1 Construction 11-2 Example 11-3 12. Introduction to Collection Classes 12-1 Concepts 12-1 Storage methods 12-2 Shallow versus deep copies 12-3 Reference-based collections 12-3 Value-based collections 12-5 Retrieving objects 12-6 Properties of objects 12-6 Retrieval methods 12-6 Iterators 12-8 13.
A more complicated example 13-7 14. “Generic” Collection Classes 14-1 Example 14-2 Declaring generic collection classes 14-4 User-defined functions 14-4 Tester functions 14-4 Apply functions 14-8 15.
Virtual functions inherited from RWSequenceable 15-14 A note on how objects are found 15-16 Hashing 15-16 16. Persistence 16-1 Operators 16-1 Example 16-2 Summary 16-6 17.
Virtual functions restoreGuts(RWFile&) and restoreGuts(RWvistream&) 17-14 Virtual function binaryStoreSize() 17-14 Persisting custom collections 17-15 Summary 17-16 18. Errors 18-1 Internal errors 18-1 Non-recoverable internal errors 18-2 Recoverable internal errors 18-4 External errors 18-6 Exception architecture 18-7 Error handlers 18-8 Debug version of the library 18-8 19.
Match memory models and other qualifiers 20-4 Use the capabilities of the library! 20-4 21. Class Reference 21-1 RWBag 21-3 RWBagIterator 21-7 RWBench 21-9 RWBinaryTree 21-14 RWBinaryTreeIterator 21-17 RWbistream 21-19 RWBitVec 21-24 RWbostream 21-30 RWBTree 21-35 RWBTreeDictionary 21-39 RWBTreeOnDisk 21-43 RWBufferedPageHeap 21-48 RRWCacheManager 21-50 RWCollectable 21-52 RWCollectableDate 21-56 RWCollectableInt 21-58 RWCollectableString 21-60 RWCollectableTime 21-62 RWCollection 21-64 .
RWCSubString 21-85 RWCTokenizer 21-88 RWDate 21-90 RWDiskPageHeap 21-98 RWDlistCollectables 21-101 RWDlistCollectablesIterator 21-105 RWFactory 21-108 RWFile 21-110 RWFileManager 21-114 RWHashDictionary 21-116 RWHashDictionaryIterator 21-120 RWHashTable 21-122 RWHashTableIterator 21-127 RWIdentityDictionary 21-129 RWIdentitySet 21-130 RWInteger 21-131 RWIterator 21-133 RWLocale 21-134 RWLocaleSnapshot 21-139 RWModel 21-142 RWModelClient 21-144 RWOrdered 21-145 RWOrderedIterator 21-149 RWpistream 21-150 104
RWpostream 21-155 RWSequenceable 21-160 RWSet 21-162 RWSetIterator 21-166 RWSlistCollectables 21-168 RWSlistCollectablesIterator 21-172 RWSlistCollectablesQueue 21-175 RWSlistCollectablesStack 21-178 RWSortedVector 21-181 RWTime 21-185 RWTimer 21-191 RWVirtualPageHeap 21-193 RWvistream 21-196 RWvostream 21-201 RWWString 21-205 RWWSubString 21-218 RWWTokenizer 21-221 RWXDRistream 21-223 RWXDRostream 21-228 RWZone 21-233 RWZoneSimple 21-236 22.
RWTIsvDlistIterator 22-11 RWTIsvSlist 22-13 RWTIsvSlistIterator 22-19 RWTPtrDlist 22-21 RWTPtrDlistIterator 22-28 RWTPtrHashDictionary 22-31 RWTPtrHashDictionaryIterator 22-36 RWTPtrHashSet 22-38 RWTPtrHashTable 22-41 RWTPtrHashTableIterator 22-45 RWTPtrOrderedVector 22-47 RWTPtrSlist 22-52 RWTPtrSlistIterator 22-58 RWTPtrSortedVector 22-61 RWTPtrVector 22-66 RWTQueue 22-69 RWTStack 22-72 RWTValDlist 22-75 RWTValDlistIterator 22-82 RWTValHashD
RWTValOrderedVector 22-100 RWTValSlist 22-105 RWTValSlistIterator 22-112 RWTValSortedVector 22-115 RWTValVector 22-120 RWTValVirtualArray 22-123 23. Classes 23-1 RWGBitVec(size) 23-1 RWGDlist(type) 23-5 RWGDlistIterator(type) 23-9 RWGOrderedVector(val) 23-12 RWGQueue(type) 23-16 RWGSlist(type) 23-19 RWGSlistIterator(type) 23-23 RWGSortedVector(val) 23-26 RWGStack(type) 23-30 RWGVector(val) 23-32 A.
C. Messages C-1 D.
xvi 104011 Tandem Computers Incorporated
Introduction 1 1.1 Overview and features Tools.h++ is a rich, robust, and versatile C++ foundation class library. By “foundation” we mean a set of classes useful for virtually any programming chore. Tools.h++ is an industry standard. It has been chosen by a wide variety of compiler vendors to be the standard library they include with every copy of their compiler. It has been ported to dozens of compilers, many operating systems, and is in use by thousands of users world wide. You can count on Tools.
1 • 1-2 Time and date handling classes Calculate the number of days between two dates, or the day of the week a date represents; read and write days or times in arbitrary formats; etc. • Internationalization support Class RWLocale provides a convenient and easy-to-use framework for internationalizing your software. Class RWTimeZone makes manipulating time zones and daylight savings time easy.
1 • File Space Manager Allocates, deallocates and coalesces free space within a file. • Still more classes... Bit vectors, virtual I/O streams, caching managers, virtual arrays, etc. • A complete error handling facility Including a facility for handling exceptions. • Online Examples The source code for examples used in the chapter “Examples” is typically found in /opt/SUNWspro/examples/Tools.h++ , depending on where you installed C++.
1 the class Object used by Smalltalk and The NIH Classes). Instead, only objects that are to be collected using the Smalltalk-like collection classes need inherit a base class RWCollectable . The advantage of this is that virtual base classes are not necessary, simplifying the inheritance tree and the difficult problem of casting from a base class back to its derived class. Simplicity.
1 names like "String", "Vector", "Stack", etc. It is also for this reason that class names and many of the potentially generic names have an "RW" prepended (e.g. , "RWBoolean"). We have worked hard to make sure that Tools.h++ is compatible with other class libraries. Secondly, the names are intended to convey as precisely as possible what the class does.
1 main() { . . // Something happens .
Compiling Programs 2 This section will tell you how to compile a program using the Tools.h++ Class Library. 2.1 Porting considerations All of the Tools.h++ header files have lower-case names of less than eight characters (plus suffix) for ease of porting between MS-DOS and UNIX. The suffix is always " .h ". Standard C++ library include files (such as ) deserve a special comment. Most manufacturers have followed the AT&T naming convention, but a few have chosen to go their own way.
2 RWDate date; // Print it out: cout << date << endl; return 0; } If this were a C program it would probably be given a suffix of .c . Unfortunately, there is no standard suffix for C++ programs. We have adopted .cc . Fortunately, most compilers can be forced to accept a different suffix.
Class Overview 3 This section gives an overview of the library and highlights some of the points of commonality between the classes. Tools.h++ provides implementation, not policy. Hence, it consists mostly of a large and rich set of concrete classes that are usable in isolation and do not depend on other classes for their implementation or semantics: they can be pulled out and used just one or two at a time.
3 “Information flow” on page 7 lists the hierarchy of all the public Tools.h++ classes. In addition, there are some other classes that are used internally by the library. 3.1 Concrete classes The concrete classes consist of • A set of simple classes (such as dates, times, strings, etc.), discussed in Chapter 5, “Strings;” Chapter , “Using Class RWDate;” and Chapter 7, “Using Class RWTime.
3 Generic collection classes “Generic collection classes” are so called because they use the preprocessor macros supplied with your C++ compiler. They can approximate templates for those compilers that do not support them. As such, they are highly portable. However, because they depend heavily on the preprocessor, they can be difficult to debug. 3.
3 3.3 Common member functions Whatever category a class might fall into, they all have very similar programming interfaces. This section highlights the common functionality. Persistence The following functions are used to store an object of type ClassName to and from an RWFile and to and from the Tools.
3 Store size RWspace RWspace ClassName::binaryStoreSize() const; ClassName::recursiveStoreSize() const; These functions return the number of bytes of secondary storage necessary to store an object of type ClassName to an RWFile using function RWFile& operator<<(RWFile& file, const ClassName&); They are useful for storing objects using classes RWFileManager and RWBTreeOnDisk .
3 Comparisons Finally, most classes have comparison and equality member functions: int RWBoolean compareTo(ClassName*) const; equalTo(ClassName*) const; and their logical operator counterparts: RWBoolean RWBoolean RWBoolean RWBoolean RWBoolean RWBoolean operator==(const ClassName&) const; operator!=(const ClassName&) const; operator<=(const ClassName&) const; operator>=(const ClassName&) const; operator<(const ClassName&) const; operator>(const ClassName&) const; 3.
3 which returns a pointer to a collection allocated off the heap with members satisfying some selection criterion. Again, you are responsible for deleting this collection when you are done with it. Both of these exceptions are documented in detail in Chapter 21, “Class Reference.” 3.5 Information flow Generally, with the Tools.h++ libraries, information flows into a function via its arguments and out through a return value. Most functions do not modify their arguments.
3 operations on objects shared across threads. Tools.h++ does enough internal locking to maintain its own internal integrity and uses appropriate multithread-safe systems calls. 3.7 Eight-bit clean All classes in Tools.h++ are eight-bit clean. This means that they can be used with eight-bit code sets such as ISO Latin-1. 3.8 Embedded nulls All classes in Tools.h++, including RWCString and RWWString , support character sets with embedded nulls. This allows them to be used with multibyte character sets. 3.
3 Public Class Hierarchy RWBench RWBitVec RWBTreeOnDisk RWCacheManager RWCollectable RWCollection RWBag RWBinaryTree RWBTree RWBTreeDictionary RWSequenceable RWDlistCollectables RWOrdered RWSortedVector RWSlistCollectables RWSlistCollectablesQueue RWSlistCollectablesStack RWHashTable RWSet RWHashDictionary RWIdentityDictionary RWIdentitySet RWCollectableDate RWCollectableInt RWCollectableString RWCollectableTime RWModelClient RWCRegexp RWCString RWCSubString RWCTokenizer RWDate RWFactory RWFile RWFileManage
3 RWGSortedVector(val) RWGStack(type) RWGVector(val) RWInteger RWIsvDlink RWIsvSlink RWIterator RWBagIterator RWBinaryTreeIterator RWDlistCollectablesIterator RWSetIterator RWHashDictionaryIterator RWOrderedIterator RWSlistCollectablesIterator RWLocale RWLocaleDefault RWLocaleSnapshot RWModel RWTime RWTimer RWTBitVec RWTIsvDlist RWTIsvSlist RWTPtrDlist RWTPtrDlistIterator RWTPtrHashTable RWTPtrHashSet RWTPtrHashTableIterator RWTPtrHashDictionary RWTPtrHashDictionaryIter
3 RWTValHashDictionary RWTValHashDictionaryIterator RWTValOrderedVector RWTValSortedVector RWTValSlist RWTValSlistIterator RWTValSlistDictionary RWTValSlistDictionaryIterator RWTValVector RWTValVirtualArray RWvios RWvistream RWbistream RWpistream RWXDRistream RWvostream RWbostream RWpostream RWXDRostream RWVirtualPageHeap RWBufferedPageHeap RWDiskPageHeap RWWString RWWSubString RWWTokenizer RWZone RWZoneSimple 104011 Tandem Computers Incorporated 3-11
3 3-12 104011 Tandem Computers Incorporated
Internationalization 4 Gone are the days when we could ignore our neighbors across the sea (or over the fence), writing software only for local consumption. Professional software development today demands not only awareness of the needs of users in other cultures, but accommodation of those needs.
4 Wide character encodings, in contrast, place each character in a 16- or 32-bit integral type called a wchar_t , and represent a string as an array of wchar_t . Usually it is possible to translate a string encoded in one form into the other. Given any of these representations for strings, there remains much to do.
4 The Standard C Library provides, with , some facilities to accommodate differences in currency, number, date, and time formats, but it is maddeningly incomplete. It offers no help for conversion from strings to these types, and is practically impossible to use if you must do conversions involving two or more locales. Common time zone facilities (such as those defined in POSIX.
4 Begin by constructing a date, today’s date: RWDate today = RWDate::now(); We can display it using ordinary “C”-locale conventions, the usual way: cout << today << endl; But what if you are in some other locale? Perhaps you have set your environment variable LANG to " fr ", or "fr_FR 1" , because you want French formatting. We would like the date to be displayed in your preferred local format.
4 RWCString str; cout << "enter a date in German: " << flush; str.readLine(cin); today = RWDate(str, german); if (today.isValid()) cout << today << endl; Sometimes you would prefer to use the extraction operator " >> ". It must know to expect and parse a German-formatted date. We can pass this information along by imbuing a stream with the German locale.
4 . For money, the main problem is that there is no standard internal representation for monetary values. Fortunately, none of these problems is overwhelming. Time Let us consider the time zone problem. Our first observation is that there is no simple relationship between time zones and locales. All of Switzerland shares a single time zone, including DST rules, but has four official languages (French, German, Italian, and Romansch).
4 The flight is about seven hours long, each way: RWTime arriveParis (leaveNewYork + long(7 * 3600)); RWTime arriveNewYork(leaveParis + long(7 * 3600)); Let’s display the Paris arrival time and date in French, and the New York arrival time and date according to local convention: RWLocaleSnapshot french("fr"); // or "fr_FR" cout << "Arrive' au Paris a' " << arriveParis.asString('c', parisZone, french) << ", heure local." << endl; cout << "Arrive in New York at " << arriveNewYork.
4 the week prior! For such jurisdictions you might best use Standard time, properly labeled: they are probably used to it. If that just won’t do, you can derive from RWZone and implement its interface for Britain alone. This is much easier than trying to make something general enough to handle all possibilities including Britain, and it’s smaller and faster besides. The remaining problem is that there is no standard way to discover what DST rules are in force for any particular place.
4 In each of the previous examples, now is disassembled into component parts twice, once to extract the hour and again for the minute. This is an expensive operation. If you expect to work with the components of a time or date much, you may be better off disassembling the time only once: RWTime now = RWTime::now(); struct tm tmbuf; now.extract(&tmbuf); const RWLocale& here = RWLocale::global(); // the default global locale cout << here.asString(&tmbuf, 'H') << ":" << here.
4 The French use “,” for the decimal point, and “.” for the digit group separator, so this might display: 1.234567e+07 1.234.567,89 987654 987.654 Numbers with digit group separators are certainly easier to read. Currency Currency conversions are trickier, mainly because there is no standard way to represent monetary values in a computer. We have adopted the convention that such values represent an integral number of the smallest unit of currency in use. For example, in the U.
4 Let us consider some examples of currency conversions: const RWLocale& here = RWLocale::global(); double sawbuck = 1000.; RWCString tenNone = here.moneyAsString(sawbuck, RWLocale::NONE); RWCString tenLocal = here.moneyAsString(sawbuck, RWLocale::LOCAL); RWCString tenIntl = here.moneyAsString(sawbuck, RWLocale::INTL); if (here.stringToMoney(tenNone, &sawbuck) && here.stringToMoney(tenLocal, &sawbuck) && here.
4 4-12 104011 Tandem Computers Incorporated
5 Strings Manipulating strings is one of the most common and error prone tasks that a programmer does. It's a perfect opportunity for C++ to show its advantages. Class RWCString has many powerful string processing features that are just as efficient as C, but far less prone to errors. For example, the class automatically takes care of memory management. It's just about impossible to delete something twice or not delete it at all. Class RWWString offers support for wide character strings.
5 Code Example 5-1 (Continued) RWCString a; RWRegexp re("V[0-9]\\.[0-9]+"); while( a.readLine(cin) ){ a(re) = "V4.0"; cout << a << endl; } return 0; } Program input: This text describes V1.2. For more information see the file install.doc. The current version V1.2 implements... Program output: This text describes V4.0. For more information see the file install.doc. The current version V4.0 implements...
5 RWCString s1, s2; cin >> s1 >> s2; cout << toUpper(s1+s2); Class RWCString has member functions to read, compare, store, restore, concatenate, prepend, and append RWCStrings and char *’s. Operators allow access to individual characters, with or without bounds checking. The details of the RWCString class capabilities are summarized in the Class Reference, Part 2. 5.
5 which is an encapsulation of the Standard C library function strcoll() . This function will return results computed according to the locale-specific collating conventions set by category LC_COLLATE of the Standard C library function setlocale() . Because this is a relatively expensive calculation, you may want to pretransform one or more strings using the global function RWCString strXForm(const RWCString&); and then use compareTo() or one of the logical operators (==, !=, etc.) on the results. 5.
5 5.4 Pattern matching Class RWCString supports a convenient interface for string searches. Here is an example. The code fragment: RWCString s("curiouser and curiouser."); int i = s.index("curious"); will find the start of the first occurrence of " curious " in s. The comparison will be case sensitive. The result is that i will be set to “0”. To find the index of the next occurrence use: i = s.index("curious", ++i); which will result in i being set to “14”.
5 #include return 0; } Program output: WM_CREATE The function call operator for RWCString has been overloaded to take an argument of type RWCRegexp . It returns an RWCSubString matching the expression, or the null substring if there is no such expression. 5.5 String I/O Class RWCString offers a rich I/O facility to and from both iostreams and Tools.h++ virtual streams.
5 Other functions allow finer tuning of RWCString input. Function readline() allows strings separated by newlines. It has an optional parameter controlling whether whitespace is skipped before storing characters. Here’s an example showing the difference: #include #include #include main() { RWCString line; { int count = 0; ifstream istr(“testfile”); while (line.readLine(istr) // Use default value: skipwhitespace count++; cout << count << “ lines, skipping whitespace.
5 Program output: 2 lines, skipping whitespace. 5 lines, not skipping whitespace. Virtual streams String operators to and from virtual streams are also supported: RWvistream&operator>>(RWvistream& vstream, RWCString& cstr); RWvostream&operator<<(RWvostream& vstream, const RWCString& cstr); This allows a string to be saved and restored without knowing the formatting that is to be used. See Chapter 16, “Persistence” for details on virtual streams. 5.
5 #include cout << i << endl; return 0; } Program output: 5 This program counts the number of tokens in the string. The function call operator for class RWCTokenizer has been overloaded to mean "advance to the next token and return it as an RWCSubString ", much like any other iterator. When there are no more tokens, it returns the null substring. Class RWCSubString has a member function isNull() which returns TRUE if the substring is the null substring. Hence, the loop is broken. 5.
5 use null bytes. You should also keep in mind that while RWCString::data() always returns a null-terminated string, there may be earlier nulls in the string. All of these effects can be summarized by the following program: RWCString a(“abc”); RWCString b(“abc\0def”); RWCString c(“abc\0def”, 7); // 1 // 2 // 3 cout << a.length(); cout << strlen(a.data()); // Prints “3” // Prints “3” cout << b.length(); cout << strlen(b.data()); // Prints “3” // Prints “3” cout << c.length(); cout << strlen(c.
5 RWCString Sun(“\306\374\315\313\306\374”); RWWString wSun(Sun, RWWString::multiByte); // MBCS to wide string RWCString check = wSun.toMultiByte(); assert(Sun==check); // OK You convert from a multibyte string to a wide string by using the special RWWString constructor RWWString(const char*, multiByte_); The parameter multiByte_ is an enum with a single possible value: multiByte , as shown in the example above.
5 5-12 104011 Tandem Computers Incorporated
Using Class RWDate 6 Class RWDate represents a date, stored as a Julian day number. It serves as a compact representation for calendar calculations, shields you from details such as leap years, and performs conversions to and from conventional calendar formats. The algorithm to convert a Gregorian calendar date (for example January 10, 1990) to a Julian day number is given in: Algorithm 199 from Communications of the ACM, Volume 6, No. 8, Aug. 1963, p. 444.
6 6.1 Example This example prints out the date 6 January 1990 and then calculates and prints the date of the previous Sunday, using the global locale: #include #include main() { RWDate dd(6, "January", 1990); cout << dd << ", a " << dd.weekDayName() << endl; RWDate prev = dd.previous("Sunday"); cout << "The previous Sunday is: " << prev << endl; return 0; } Program output: 6-Jan-90, a Saturday The previous Sunday is: 31-Dec-89 6.
6 3. Construct a RWDate (1–12) and year: for a given day of the month (1–31), month number RWDate d(10, 3, 90); 4. Construct a RWDate // 3/10/1990 from a RWTime : RWTime t; RWDate d(t); // Current time. In addition, you can construct a date using locale-specific strings. If you do nothing, a “default locale” will be used.
6 1. A “snapshot” is taken of locale "fr ". This assumes that your system supports this locale. Another common name for this locale is " fr_FR ". 2. A date is constructed using the constructor RWDate(unsigned day, const char* month, unsigned year, const RWLocale& locale = RWLocale::global()); Note – the second argument " month " is meaningful only within the context of a locale. In this case, we are using the locale constructed at line 1. The result is the date (as known in English) of June 10, 1990. 3.
Using Class RWTime 7 Class RWTime represents a time, stored as the number of seconds since 1 January 1901 UTC. While UTC is a widely accepted time standard, it is not the usual time reference that most people use in their day-to-day lives. We tell time with a “local” time which may or may not observe daylight savings time (DST). In addition, DST may or may not actually be in effect. Hence, when we create an RWTime object, we are unlikely to do so with UTC.
7 7.2 Constructors A RWTime may be constructed in several ways: 1. Construct a RWTime with the local time: RWTime t; 2. Construct a RWTime with today's date, at the specified local hour (0–23), minute (0–59) and second (0–59): RWTime t(16, 45, 0); 3. Construct a RWTime for a given date and local time: RWDate d(2, "June", 1952); RWTime t(d, 16, 45, 0); 4. Construct a RWTime //today 16:45:00 // 6/2/52 16:45:003.
7 RWDate today; // Current date RWTime dstStart = RWTime::beginDST(today.
7 7-4 104011 Tandem Computers Incorporated
VirtualStreams 8 The “iostream” facility that comes with every C++ compiler is a resource that is familiar to every C++ programmer. Among its advantages are type safe insertion and extraction into and out of streams and extensibility to new types. Furthermore, the source and sink of the bytes of the stream are set by another class ( streambuf ) and are completely transparent to the user of the streams. But it suffers from a number of limitations.
8 The Tools.h++ “virtual streams” overcomes these limitations by offering an idealized model of a stream. No assumptions are made about formatting, or stream models. At the bottom of the virtual streams class hierarchy is class RWvios .
8 Inheriting from RWvios are abstract base classes RWvistream and RWvostream .
8 with whitespace, commas, or any other kind of formatting. You are effectively telling RWvostream , “Here is a double. Please store it for me in whatever format is convenient and give it back to me in good shape when I ask for it”. The results are extremely powerful. You can not only use, but also write, streaming operators without knowing anything about the final output medium or formatting that is to be used. For example, the output medium could be a disk, memory allocation, or even a network.
8 8.2 Simple example Here's a simple example that exercises RWbostream and RWbistream through their respective abstract base classes, RWvostream and RWvistream : #include #include #include
8 cout << b << endl; return 0; } Program output: A string with newline. A string with newline. tabs and a tabs and a The job of function save(RWCString& a, RWvostream& v) is to save the string a to the virtual output stream v. Function recover(RWvistream& ) restores the results. These functions do not know the ultimate format with which the string will be stored. Some additional comments on particular lines: 1–2 On these lines, a file output stream f is created for the file " junk.dat".
8 Unfortunately, at the time of this writing, most implementations of seekg() have not proven to be reliable. Hence, this approach was not chosen for this example. 8.3 Recap We have seen how an object can be stored and recovered from streams without regard to the final destination of the bytes of that stream. They could reside in memory, or on disk. We have also seen how we need not be concerned with the final formatting of the stream. It could be in ASCII or binary.
8 8-8 104011 Tandem Computers Incorporated
9 Using Class RWFile Class RWFile encapsulates the standard C file operations for binary read and write, using the ANSI-C function fopen() , fwrite() , fread() , etc. This class is patterned on class PFile of the Interviews Class Library (1987, Stanford University), but has been modified (and modernized) by Tools.h++ to use "const " modifiers. The member function names begin with upper case letters in order to maintain compatibility with class PFile .
9 9.1 Example Class RWFile has member functions to determine the status of a file, and to read and write a wide variety of built in types, either one at a time, or as arrays. The file pointer may be repositioned with functions SeekTo() , SeekToBegin() , and SeekToEnd() . The details of the RWFile class capabilities are summarized in Part 2: Class Reference. For example, to create a RWFile with filename " test.
Using Class RWFileManager 10 Class RWFileManager allocates, deallocates and coalesces free space in a disk file. This is done internally by maintaining on disk a linked-list of free space blocks. Two typedefs are used: typedef long typedef unsigned long RWoffset; RWspace; The type RWoffset is used for the offset within the file to the start of a storage space; RWspace is the amount of storage space required. The actual typedef may vary depending on the system you are using.
10 10.2 Member functions The class RWFileManager class RWFile . They are: adds four additional member functions to those of 1. RWoffset allocate(RWspace s); Allocate s bytes of storage in the file, returning the offset to the start of the allocation. 2. void deallocate(RWoffset t); Deallocate (free) the storage space starting at offset t. This space must have been previously allocated by the function allocate() : 3. RWOffset endData(); Return the offset to the last data in the file. 4.
10 The following example shows the use of class RWFileManager to construct a linked-list of ints on disk: The source code is included in the toolexam subdirectory as example7.cc and example8.cc . Code Example 10-1 #include #include // 1 struct DiskNode { int data; RWoffset nextNode; }; // 2 // 3 // 4 main() { RWFileManager fm("linklist.dat"); // 5 // Allocate space for offset to start of the linked list: fm.
10 Code Example 10-1 fm.Write(n.nextNode); return 0; } // 17 Here's a line-by-line description of the program: 10-4 1. Include the declarations for the class RWFileManager . 2. Struct DiskNode 3. The data (an int), and 4. The offset to the next link. RWoffset int. 5. This is the constructor for an RWFileManager . It will create a new file, called " linklist.dat ." 6. Allocate space on the file to store the offset to the first link.
10 14. Since we allocate the next link before we write the current link, the final link in the list will have an offset to an allocated block that is not used. It must be handled as a special case. 15. First, deallocate the final unused block. 16. Next, reassign the offset of the final link to be RWNIL . When the list is read, this will indicate the end of the linked list. Finally, re-write the final link, with the correct information. 17.
10 Here's a line-by-line description of the program: 10-6 1. The RWFileManager 2. The member function start() returns the offset to the first space ever allocated in the file. In this case, that space will contain an offset to the start of the linked-list. 3. Read the offset to the first link. 4. A loop to read through the linked-list and print each entry. 5. Seek to the next link. 6. Read the next link. 7. Print the integer. 8. Get the offset to the next link. 9.
Using Class RWBTreeOnDisk 1 Class RWBTreeOnDisk has been designed to manage a B-Tree in a disk file. The class represents an ordered collection of associations of keys and values, where the ordering is determined internally by comparing keys. Given a key, a value can be retrieved. Duplicate keys are not allowed. Keys are arrays of chars . The key length is set by the constructor. The ordering in the B-Tree is determined by comparing keys with an external function. You can change this function.
11 functions to add a key-value pair, find a key, remove a key, operate on all keyvalue pairs in order, return the number of entries in the tree, and determine if a key is contained in the tree. 11.1 Construction A RWBTreeOnDisk is always constructed from a RWFileManager . If the RWFileManager is managing a new file, then the RWBTreeOnDisk will initialize it with an empty root node. For example, the following code fragment constructs a RWFileManager for a new file called "filename.
11 11.2 Example In this example, key-value pairs of character strings and offsets to RWDates, representing birthdays, are stored. Given a name, a birthdate can be retrieved from disk. #include #include #include #include #include main() { RWCString name; RWDate birthday; RWFileManager fm(“birthday.dat”); RWBTreeOnDisk btree(fm); while (cin >> name) { cin >> birthday; RWoffset loc = fm.allocate(birthday.binaryStoreSize()); fm.
11 5. Seek to the location where the RWDate will be stored. 6. Store the date at that location. Most Tools.h++ classes have an overloaded version of the streaming (<< and >>) operators. 7. Insert the key and offset to the object in the B-Tree. Having stored the names and birthdates on a file, here's how you might retrieve them: #include #include #include #include #include
11 2. The name is used as a key to the RWBTreeOnDisk , which returns the associated value, an offset into the file. 3. Check to see whether the name was found. 4. If the name was valid, use the value to seek to the spot where the associated birthday is stored. 5. Read the birthdate from the file. 6. Print it out. With a little effort it is easy to have more than one B-Tree active in the same file. This allows you to maintain indexes on more than one key.
11 And here is how you could open the three B-Trees: #include #include main() { RWoffset rootArray[3]; // Location of the tree roots RWBTreeOnDisk* treeArray[3];// Pointers to the RWBTreeOnDisks RWFileManager fm(“index.dat”); fm.SeekTo(fm.start()); // Recover locations of root nodes fm.
Introduction to Collection Classes 12 The Tools.h++ class library includes three different types of collection classes: • A set of template-based collection classes; • A set of "generic" collection classes, modeled after Stroustrup (1986), Chapter 7.3.5; • A set of Smalltalk-like collection classes. Despite their very different implementations, their functionality, as well as their user-interfaces (member function names, etc.), is very similar.
12 Storage methods There are two different ways to store an object in a collection: either store the object itself ( value-based collections) or store a pointer or reference to the object (reference-based collections). The difference can have important consequences. Value-based collections are simpler to understand and manipulate. You create, say, a linked list of integers or doubles. Or a hash table of shorts. The stored type can be more complicated: for example, RWCStrings .
12 Shallow versus deep copies Reference-based collections What happens when you make a copy of a reference-based collection? It turns out that this is a more general issue: it doesn't just affect collection classes, but any class that references another object. Hence, if the type of object that a value-based collection is collecting is an address, then this issue will arise there too. There are two general approaches: shallow copying and deep copying. 1.
12 Before Peggy Fred Lee Nell Figure 12-1 Bag before a copy A shallow and deep copy of this collection would look like (respectively): Shallow Copy Bag 1 Deep Copy Bag 2 Bag 1 Bag 2 Peggy Peggy Peggy Fred Fred Fred Lee Lee Lee Nell Nell Nell Figure 12-2 Shallow and deep copy of collection Note – The deep copy not only made a copy of the bag itself, but also, recursively, any objects within it.
12 Although shallow copies can be useful (and fast, because less copying is done), one must be careful because two collections now reference the same object. If you delete all the items in one collection, you will leave the other collection pointing into nonsense. The issue of shallow versus deep copies can also arise when an object is written to disk. If an object includes two or more pointers or references to the same object, then when it is restored it is important that this morphology be preserved.
12 12.2 Retrieving objects Properties of objects Every object that you create has three properties associated with it: 1. Its "type" ( e.g. , a RWCString or a "double"). In C++, an object's type is set at creation. It cannot change. 2. Its "state" ( i.e., the value of the string). The values of all the instance variables or attributes of an object determine its state. These can change. 3. Its "identity" (i.e., identifies an object uniquely and for all time).
12 1. Find an object with a particular state. An example is testing two strings for the same value. In the literature, this is frequently referred to as two objects testing "isEqual", having "equality", "compares equal", having the same "value", or testing true for the "=" operator. Here, we will refer to the two objects as testing equal ("isEqual").
12 Suppose you were maintaining a mailing list. Given a person's name, you want to find his or her address. In this case, you would want to search for a name that is equal to the name at hand. A Dictionary would be appropriate. The key to the Dictionary would be the name, the value would be the address. Suppose you are writing a hypertext application. You need to know in which document a particular graphic occurs. This might be done by keeping a Dictionary of graphics and their corresponding document.
12 The rule is "advance and then return." All Tools.h++ iterators work this way. 1 If you change the collection by adding or deleting objects while an iterator is active, the state of the iterator also becomes undefined—using it could bring unpredictable results. The member function reset() will restart the iterator, as if it had just been constructed. At any given moment the iterator "marks" an object in the collection. You can think of it as the "current" object.
12 For most collections, using member function apply() to access every member is much faster than using an iterator. This is particularly true for the sorted collections—usually a tree has to be traversed, requiring that the parent of a node be stored on a stack. Function apply() uses the program's stack, while the sorted collection iterator must maintain its own. The former is much faster.
Templates 13 13.1 Introduction Ever since Version 2.0, Tools.h++ has traditionally offered two types of collection classes: the so-called "generic" collection classes and the Smalltalklike collection classes. Each had its advantages and disadvantages. The Smalltalk-like classes offer a pleasant programming interface, code reuse, and a consistent interface.
13 Enter templates Templates, or parameterized types, offer an elegant solution. Over the next few years they promise to revolutionize the way we approach C++ programming. Indeed, 5 years from now the polymorphic collection approach may be just a footnote in the history of C++ design. Templates are extremely similar to the "generic.h" approach, described in the following section, which relies on preprocessor macros to define a family of classes parameterized on a type.
13 want to declare a BaseVector class that holds the length of any vector. We would then derive the template-based vectors Vector from this. Of course, the code required to return the length of a vector is trivial, and so it turns out that in practice it isn't worth doing this. Factoring out commonality For a more substantial example, take a look at the intrusive linked-list class RWTIsvSlist . This is a linked list of types T which are required to inherit from class RWIsvSlink .
13 13.3 Types of templates Intrusive lists For a collection of type T, intrusive lists are lists where type T inherits directly from the link type itself 1. The results are optimal in space and time, but require you to honor the inheritance hierarchy. Value-based collections Value-based collections copy the object in and out of the collection.
13 Pointer-based collections The final type of collection, pointer-based, is similar to the Smalltalk-like collection classes. The data that gets inserted into the collection is not the object itself, but rather its address. That is, a pointer to the data is inserted.
13 Code Example 13-1 (Continued) vec.reshape(30); for (i=21; i<30; i++) return 0; // 5 // 6 vec[i] = 3.0; } Each program line is detailed below. 1. This is where the template for RWTValVector is defined. 2. A vector of doubles, 20 elements long and initialized to 0.0 is declared and defined. 3. The first 10 elements of the vector are set to 1.0. Here, RWValVector::operator[](int) has been used. This operator always performs a bounds check on its argument. 4.
13 13.5 A more complicated example Here's another example, this one involving a hashing dictionary. #include #include #include #include class Count { int N; public: Count() : int operator }; // 1 N(0) { } operator++() { return ++N; } int() { return N; } // 2 // 3 // 4 unsigned hashString ( const RWCString& str ) { return str.
13 Program output: much wood a if woodchuck could chuck How ? 1 2 2 1 2 2 2 1 1 The problem is to read an input file, break it up into tokens separated by whitespace, count the number of occurences of each token, and then print the results. The general approach is to use a dictionary to map each token to its respective count. Here's a line-by-line description: 13-8 1. This is a class used as the value part of the dictionary. 2. A default constructor is supplied that zeroes out the count. 3.
13 which is what the while loop will actually be testing. Operator void* returns " this " if the stream state is "good", otherwise zero. Because an EOF causes the stream state to turn to "not good", the while loop will be broken when an EOF is encountered. See the RWCString entry in the class reference guide and the ios entry in the class reference guide that comes with your compiler for more details. 8. Here's where all the magic occurs. Object map is the dictionary.
13 13-10 104011 Tandem Computers Incorporated
“Generic” Collection Classes 14 This chapter describes the second kind of collection classes included in the Tools.h++ Class Library: generic collection classes. They are so-called because they use the macros defined in , an early approximation to parameterized types, first described in Stroustrup (1986, p. 209). While they can be more unwieldy than true templates 1, they do offer the advantage of being portable to any C++ compiler, even older compilers.
14 14.1 Example Here is an example of using a RWGStack (generic stack) to store a set of pointers to ints in a last-in, first-out (LIFO) stack. We will go through it lineby-line and explain what is happening: #include #include // // 1 2 declare(RWGStack, int) main() { RWGStack(int) gs; gs.push(new int(1)); gs.push(new int(2)); gs.push(new int(3)); gs.push(new int(4)); cout << "Stack now has " << gs.
14 (class RWSlist ). It is restricted because only certain member functions of RWSlist can be used (those appropriate to stacks) and because the items to be inserted into the stack must be of type type . 2. is a special Tools.h++ supplied header file that includes with the appropriate suffix, depending on your compiler. 3. This line invokes the macro declare which is defined in the header file , supplied with your compiler.
14 14.2 Declaring generic collection classes All of the Tools.h++ generic collection classes are declared using the declare macro, defined in the header file , in a manner similar to the example above. However, there is one important difference in how the Tools.h++ classes are declared versus the pattern set by Stroustrup (1986, Section 7.3.5). This is summarized below: typedef int* intP; declare(RWGStack, intP) declare(RWGStack, int) // Wrong! // Correct.
14 Here is an example that expands on the Example in “Example” on page 2. The problem is to push some values onto a stack and then to see if a certain value exists on the stack (test for "isEqual"). The member function contains() of class RWGStack (type ) has prototype: RWBoolean contains ( RWBoolean (*t)(const type *, const void*), const void* a ) const; The first argument is RWBoolean (*t)(const type *, const void*) .
14 Program output: Yup. A description of each program line follows. 1. This is the tester function. The first argument is a pointer to the type of objects in the collection, ints in this case. The second argument points to an object that can be of any type. In this example, it also points to an int . Both arguments are declared const pointers — in general the tester function should not change the value of the objects being pointed to. 2.
14 The following is an example where they are not of the same type: #include #include class Foo { public: int data; Foo(int i) {data = i;} }; declare(RWGStack, Foo) // A stack of pointers to Foos RWBoolean anotherTesterFunction(const Foo* fp, const void* a) { return fp->data == *(const int*)a; } main() { RWGStack(Foo) gs; gs.push(new Foo(1)); gs.push(new Foo(2)); gs.push(new Foo(3)); gs.push(new Foo(4)); int aValue = 2; if ( gs.
14 Apply functions The second kind of user-defined function is an "apply function". Its general form is: void yourApplyFunction (type * ty, void* a) where yourApplyFunction is the name of the function and type is the type of the members of the collection. Apply functions give you the opportunity to perform some operation on each member of a collection (perhaps print it out or draw it on a screen).
14 Program output: 1 2 3 4 The items are appended at the tail of the list (see Part 2: Class Reference). For each item, the apply() function calls the user-defined function printAFoo() with the address of the item as the first argument and the address of an ostream (an output stream) as the second argument. The job of printAFoo() is to print out the value of member data val . Because apply() scans the list from beginning to end, the items will come out in the same order in which they were inserted.
14 14-10 104011 Tandem Computers Incorporated
15 Smalltalk-like Collection Classes 15.1 Introduction The third general type of collection classes provided with the Tools.h++ Class Library is a set of "Smalltalk-80-like Collection Classes". In this approach, objects to be collected must inherit the abstract base class " RWCollectable ", using either single or multiple inheritance. The principal advantage of this approach is that the programming-interface is much cleaner and the collection classes are far more powerful.
15 Table 15-1 Smalltalk-like classes, iterators, and implementations.
15 Table 15-2 lists the class hierarchy of the Smalltalk-like collection classes. Note – Some of these classes use multiple-inheritance: this hierarchy is shown relative to the RWCollectable base class.
15 15.2 Example To get us oriented, it is always good to look at an example. This code uses a SortedCollection to store and order a set of RWCollectableStrings . We will go through it line-by-line and explain what is happening: #define RW_STD_TYPEDEFS 1 #include #include #include main() { // Construct an empty SortedCollection SortedCollection sc; // Insert some RWCollectableStrings: sc.insert(new RWCollectableString("George")); sc.
15 1. By defining the preprocessor macro RW_STD_TYPEDEFS we enable the set of Smalltalk-like typedefs. This enables us to use the generic name "SortedCollection " instead of RWBinaryTree , its true identity. 2. The second #include declares class RWCollectableString which is a derived class with classes RWCString and RWCollectable as base classes. Multiple inheritance was used to create this class. Most of its functionality is inherited from class RWCString .
15 15.3 Overview This section gives a general overview of the various Smalltalk-like collection classes to help you chose an appropriate one for your problem. Bags versus Sets versus Hash Tables Class RWHashTable is the simplest to understand. It uses a simple hashed lookup to find the "bucket" that a particular object occurs in, then does a linear search of the bucket to find the object.
15 Sequenceable classes Classes inheriting from RWSequenceable have an inate ordering. That is, it is meaningful to speak of the "6'th object", or the "first" or "last" object. These classes are generally implemented either as a vector or as a singly- or doubly-linked list. You should be aware of the differences: vector based classes make good stacks and queues, but are poor at insertions in the middle.
15 15.4 Virtual functions inherited from RWCollection The Smalltalk-like collection classes inherited from the abstract base class RWCollection which, in turn, inherits from the abstract base class RWCollectable , described in Chapter 17, “Designing an RWCollectable Class” (making it is possible to have collections of collections). An "abstract base class" is a class that is not intended to be used per se, but rather to be inherited by some other class.
15 These functions test how many objects the collection contains and whether it contains a particular object. The function isEmpty() returns true if the collection contains no objects. The function entries() returns the total number of objects that the collection contains. The function contains() returns TRUE if the argument is equal to an item within the collection. The meaning of "is equal to" depends on the collection and the type of object being tested.
15 Code Example 15-1 (Continued) if(t){ if(t-isA() == dummy.isA()) cout << *(RWCollectableString*)t << "\n"; } else cout << "Object not found.\n"; // 12 // 13 // 14 cout << sc.occurrencesOf(&dummy) << "\n"; return 0; // 16 // 15 } Program output: 5 Mary 2 Here's the line-by-line description: 1–7. 15-10 These lines are as in “Example” on page 4. 8. Insert another instance with the value "Mary". 9. This statement prints out the total number of entries in the sorted collection: 5. 10.
15 15. If the pointer t here. was nil, then an error message would have been printed 16. The call to occurrencesOf() returns the number of items that compare equal to its argument. In this case, two items are found (the two occurrences of "Mary"). remove() functions virtual RWCollectable* remove(const RWCollectable*); virtual void removeAndDestroy(const RWCollectable*); The function remove() looks for an item that is equal to its argument and removes it from the collection, returning a pointer to it.
15 apply() functions virtual void apply(RWapplyCollectable ap, void* x); An efficient method for examining the members of a Smalltalk-like collection is member function apply() . The first argument ( RWapplyCollectable ) is a typedef: typedef void(*RWapplyCollectable)(RWCollectable*, void*); that is, a pointer to a function with prototype: void yourApplyFunction (RWCollectable* item, void* x) where yourApplyFunction is the name of the function. You must supply this function.
15 Functions clear() and clearAndDestroy() virtual void virtual void The function clear() clear(); clearAndDestroy(); removes all items from the collection. The function clearAndDestroy() not only removes the items, but also calls the virtual destructor for each item. Although it does check to see if the same item occurs more than once in a collection (by building an IdentitySet internally) and thereby deletes each item only once, it must still be used with care.
15 Selection typedef RWBoolean (*RWtestCollectable)(const RWCollectable*, const void*); RWCollection* select(RWtestCollectable tst, void*); The function select() 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 of the same type as self and returns a pointer to it. This new collection is allocated off the heap, hence you are responsible for deleting it when done. 15.
15 These functions return the first or last item in the collection, respectively, or nil if the collection is empty. virtual size_t index(const RWCollectable*) const; This function returns the index of the first object that is equal to the argument or the special value " RW_NPOS " if there is no such object: RWOrdered od; od.insert(new RWCollectableInt(6)); od.insert(new RWCollectableInt(2)); od.insert(new RWCollectableInt(4)); // 6 // 6 2 // 6 2 4 RWCollectableInt dummy(2); size_t inx = od.
15 15.7 A note on how objects are found ! Caution – It is important to note that it is the virtual functions of the object within the collection that gets called when comparing or testing a target for equality, not that of the target. For example, consider the following code fragment: SortedCollection sc; RWCollectableString member; sc.insert(&member); RWCollectableString target; RWCollectableString* p = (RWCollectableString*)sc.
Persistence 16 All of the examples of persistence that we have looked at so far involve simple objects that do not reference other objects. It is time to look at some more complicated cases. 16.1 Operators The storage and retrieval of objects that inherit from RWCollectable is a powerful and adaptable feature of the Tools.h++ Class Library.
16 These function not only allow the storage and retrieval of collections and their inserted objects, but also their morphology. For example, a collection with multiple pointers to the same object could be be saved and restored. Or a circularly linked list. Note – this ability to restore the morphology of an object is a property of the base class RWCollectable .
16 // Store in ascii to standard output: RWpostream ostr(cout); ostr << sc; // 1 // 2 bt.clearAndDestroy(); // 3 return 0; } Note – we have inserted one item into the collection twice. That is, two items in the collection are identical. Graphically, the object bt looks something like this: The expression on line 2 called the function RWvostream&operator<<(RWvostream&, const RWCollectable&); which stored a shallow copy of the collection. That is, only only one copy of “George” was stored.
16 // Read the collection back in: istr >> sc2; // 4 RWCollectableString temp("George"); // 5 // Find a "George": RWCollectableString* g = (RWCollectableString*)sc2.find(&temp); // 6 // "g" now points to a string with the value "George" // How many occurrences of g are there in the collection? unsigned count = 0; SortedCollectionIterator sci(sc2); RWCollectableString* item; while ( item = (RWCollectableString*)sci() ) if ( item==g ) count++; // 7 // 8 // 9 //10 cout << count; sc2.
16 7 Here’s how we can prove that there are actually two entries in the collection that point to the same George. Initialize a counter to zero. 8 As before, create an iterator from the collection. 9 Iterate through the collection, item by item, returning a pointer for each item. 10 Test whether this pointer equals g. That is, test for identity, not just equality. 11 Delete the objects created in line 4.
16 However, you do not have to know these details until you write your own class RWCollectable class, something we will do in the following chapter. However, at this point, you should note that when Smalltalk-like collection classes are restored they necessarily do not know the types of objects they will be restoring. Hence, they must allocate them off the heap. This means that you are responsible for deleting the restored contents. This happened in line 11 of the example. 16.
16 Finally, there are two operators for retrieval into a reference to a RWCollectable pointer: RWvistream& operator>>(RWvistream&, RWCollectable*& obj); // 7 RWFile& operator>>(RWFile&, obj); RWCollectable*& // 8 As mentioned in the previous section, these last two operators allocate an object off the heap , restore into it, then return a reference to the resultant pointer. You are responsible for deleting this object when done.
16 16-8 104011 Tandem Computers Incorporated
Designing an RWCollectable Class 17 Up until now we have been persisting classes that come with Tools.h++. In this section we will look at how to create our own subclass of RWCollectable . This will allow it to use the persistence machinery or to be used by the Smalltalk-like collection classes. 17.
17 (RWBoolean is a typedef for an int , RWspace is a typedef for unsigned long , and RWClassID is a typedef for an unsigned short .) Any class that derives from class RWCollectable should be able to understand any of these methods. Although default definitions are given for all of them in the base class RWCollectable , it is best for the class designer to provide definitions that are tailored to the class at hand. 17.2 Example Suppose we are running a bus company.
17 Bus(); Bus(int busno, const RWCString& driver); ~Bus(); // Inherited from class "RWCollectable": RWspace binaryStoreSize() const; int compareTo(const RWCollectable*) const; RWBoolean isEqual(const RWCollectable*) const; unsigned hash() const; void restoreGuts(RWFile&); void restoreGuts(RWvistream&); void saveGuts(RWFile&) const; void saveGuts(RWvostream&) const; void void size_t size_t RWCString int addPassenger(const char* name); addCustomer(const char* name); customers() const; passengers() const; dri
17 • Define a default constructor; • Add the macro RWDECLARE_COLLECTABLE • Add the macro RWDEFINE_COLLECTABLE • Add definitions for the following inherited virtual functions as necessary (you may be able to use inherited definitions): RWspace int RWBoolean unsigned void void void void to your class declaration; to a .
17 17.5 RWDECLARE_/RWDEFINE_COLLECTABLE() Note – the macro invocation “ RWDECLARE_COLLECTABLE (className)” in the declaration for Bus . You must put this macro in your class declaration 1, using the class name as the argument. This macro automatically inserts declarations for functions isA() and newSpecies() . A corresponding macro “ RWDEFINE_COLLECTABLE (className, classID )” must be put in your .cc file, using the class name as the first argument, and its chosen class ID as the second number (see below).
17 Virtual function newSpecies() The job of this function is to return a pointer to a brand new object of the same type as self. The declaration of this function is automatically provided by the macro RWDECLARE_COLLECTABLE (className). The definition is automatically provided by the macro RWDEFINE_COLLECTABLE (className,classID ). An aside: the RWFactory As mentioned, you must include the macro RWDEFINE_COLLECTABLE somewhere in a .cc file where it will be compiled.
17 never appear outside the scope of the class, we do not have to worry about the user having access to them. Hence, we can confidently delete them in the destructor, knowing that no dangling pointers will be left. Furthermore, because the set pointed to by customers_ is a superset of the set pointed to by passengers_, it is only necessary, indeed, it is essential, that we only delete the contents of customers_ . Here’s a possible definition: Bus::~Bus() { customers_.
17 The default definition (comparing the addresses of the two objects) should really be thought of as a placeholder—in practice, it is not very useful and could vary from run-to-run of a program. Here is an example that uses compareTo() hash() . as well as isEqual() and RWCollectableString a(“a”); RWCollectableString b(“b”); RWCollectableString a2(“a”); a.compareTo(&b); a.compareTo(&a2); b.compareTo(&a); // Returns -1 // Returns 0 (“compares equal”) // Returns 1 a.isEqual(&a2); a.
17 Note – there are many other possible choices—we could have used the driver name, in which case they would have been sorted by that. Which choice you use will depend on your particular problem. Of course, there is a hazard here. We have been glib in assuming that the actual type of the RWCollectable which c points to is always a Bus .
17 There is no formal requirement that two objects which “compare equal” (i.e., compareTo() returns zero) must also return TRUE from isEqual() , although it is hard to imagine a situation where this wouldn’t be the case. For our example above, an appropriate definition might be: RWBoolean Bus::isEqual(const RWCollectable* c) const { const Bus* b = (const Bus*)c; return busNumber_ == b->busNumber_; } Here we are considering busses to be “equal” if their bus numbers are the same.
17 17.10 How to add persistence To add persistence to your RWCollectable class, you must override the saveGuts() and restoreGuts() virtual member functions such that they write out all of your object’s member data. Virtual functions saveGuts(RWFile&) and saveGuts(RWvostream&) These virtual functions are responsible for storing the internal state of an RWCollectable object on either a binary file (using class RWFile ) or on a virtual output stream (an RWvostream ).
17 With these rules in mind, here is a possible definition for our Bus example: void Bus::saveGuts(RWFile& f) const { RWCollectable::saveGuts(f); // Save base class f.Write(busNumber_); // Write primitive directly f << driver_ << customers_; // Use Tools.
17 would be disastrous as we would have to dereference passengers_ : strm << *passengers_; Instead, we pass it to RWvostream& operator<<(RWvostream&, const RWCollectable*); which automatically detects the nil pointer and stores a record of it. Multiply-referenced objects Note – a passenger name can exist in the set pointed to by customers_ and in the set pointed to by passengers_ . That is, both collections contain the same string.
17 Virtual functions restoreGuts(RWFile&) and restoreGuts(RWvistream&) In a similar manner to saveGuts() , these virtual functions are used to restore the internal state of an RWCollectable from a file or stream. Here is a definition for Bus : void Bus::restoreGuts(RWFile& f) { RWCollectable::restoreGuts(f); // Restore base class f.Read(busNumber_); // Restore primitive f >> driver_ >> customers_; // Uses Tools.
17 is used to calculate the number of bytes necessary to store an object using RWFile . This is useful for classes RWFileManager and RWBTreeOnDisk which require space to be allocated for an object before it can be stored. Writing a version of binaryStoreSize() is usually very straightforward. Just follow the pattern set by saveGuts(RWFile&) , except that instead of saving member data, add up their sizes.
17 RWvistream& operator>>(RWvistream&, RWCollectable*&); which will allocate a new object of the proper type off the heap, followed by insert() . Because all of the Tools.h++ Smalltalk-like collection classes inherit from RWCollection , they all use this mechanism. If you decide to write your own collection classes and inherit from class RWCollection , you will rarely have to define your own saveGuts() or restoreGuts() . There are exceptions.
17 Bus(); Bus(int busno, const RWCString& driver); ~Bus(); // Inherited from class "RWCollectable": RWspace binaryStoreSize() const; int compareTo(const RWCollectable*) const; RWBoolean isEqual(const RWCollectable*) const; unsigned hash() const; void restoreGuts(RWFile&); void restoreGuts(RWvistream&); void saveGuts(RWFile&) const; void saveGuts(RWvostream&) const; void void size_t size_t RWCString int addPassenger(const char* name); addCustomer(const char* name); customers() const; passengers() const; dri
17 #endif RWDEFINE_COLLECTABLE(Bus, 200) Bus::Bus() : busNumber_ (0), driver_ ("Unknown"), passengers_ (rwnil) { } Bus::Bus(int busno, const RWCString& driver) : busNumber_ (busno), driver_ (driver), passengers_ (rwnil) { } Bus::~Bus() { customers_.clearAndDestroy(); delete passengers_; } RWspace Bus::binaryStoreSize() const { RWspace count = RWCollectable::binaryStoreSize() + customers_.recursiveStoreSize() + sizeof(busNumber_) + driver_.
17 } RWBoolean Bus::isEqual(const RWCollectable* c) const { const Bus* b = (const Bus*)c; return busNumber_ == b->busNumber_; } unsigned Bus::hash() const { return (unsigned)busNumber_; } size_t Bus::customers() const { return customers_.entries(); } size_t Bus::passengers() const { return passengers_ ? passengers_->entries() : 0; } void Bus::saveGuts(RWFile& f) const { RWCollectable::saveGuts(f); // Save base class f.Write(busNumber_); // Write primitive directly f << driver_ << customers_; // Use Tools.
17 strm << passengers_; // Will detect nil pointer automatically } void Bus::restoreGuts(RWFile& f) { RWCollectable::restoreGuts(f); f.Read(busNumber_); f >> driver_ >> customers_; delete passengers_; f >> passengers_; // Restore base class // Restore primitive // Uses Tools.
17 { Bus theBus(1, "Kesey"); theBus.addPassenger("Frank"); theBus.addPassenger("Paula"); theBus.addCustomer("Dan"); theBus.addCustomer("Chris"); { ofstream f("bus.str"); RWpostream stream(f); stream << theBus; // Persist theBus to an ASCII stream } { ifstream f("bus.str"); RWpistream stream(f); Bus* newBus; stream >> newBus; // Restore it from an ASCII stream cout << "Bus number " << newBus->number() << " has been restored; its driver is " << newBus->driver() << ".
17 17-22 104011 Tandem Computers Incorporated
Errors 18 Thinking about error handling is like thinking about where the garbage man hauls your trash—it’s a messy, unpredicatable, and sour topic, one that we don’t like to think about. Yet, to write robust code, think about it we must. The Tools.h++ class libraries use an extensive and complete error handling facility, all based on the same model. Errors are divided into two broad categories: internal errors and external errors.
18 In theory, all of these errors are preventable. For example, the permissible range of indices for an array is always known, and so a bounds error should be avoidable. As another example, while your program may not know that a date is bad, once it has found this out, to use it would be an obvious logic error.
18 An example is bounds checking: the cost of checking to make sure an index is in range can well exceed the cost of the array access itself. If a program does a lot of array accesses, checking every one may result in a slow program. To avoid this, the library may require that the user always use a valid index. Because a minimum level of correctness is being demanded, non-recoverable errors must be relatively easy to avoid and simple in concept.
18 Recoverable internal errors Distinguishing characteristics: • Similar to “Non-recoverable internal errors” (see above) except: • Cost of detection is low. • Detected in the debug and production version of the library. Examples: • Attempt to use an invalid date • Bounds error in a linked list Response: • Throw an exception inheriting from RWInternalErr .
18 Note – Note how the function always attempts to detect a bounds error. If it finds one, then it throws an instance of RWBoundsErr , a class that inherits from RWInternalErr . This instance contains an (internationalized) message (discussed in “Localizing messages” on page 9” in Chapter 19, “Implementation Notes”). The RWTHROW macro is discussed in “Error handlers” on page 8. Throwing an exception gives you the opportunity to catch the exception and, possibly, recover.
18 18.2 External errors Distinguishing characteristics: • Cannot reasonably predict them in advance. • Usually occur at a more abstract level. • Hence, cost of detection is relatively low. • Detected in all versions of the library. Examples: • Attempt to set a bad date (E.g., “31 June 1992”). • Attempt to invert a singular matrix. • Stream write error. • Out of memory. Response: • Throw an exception inheriting from RWInternalErr; • Or provide a test for object validity.
18 Note – Note that the line between an internal and external error can sometimes be fuzzy. For example, the rules could say “don’t give me an invalid date” and then the programmer would be responsible for detecting a bad date before using a Tools.h++ routines. Of course, this is a lot of work and probably the reason why you bought the library in the first case: the RWDate object is probably in a much better position than you to detect invalid dates.
18 As you can see, the hierarchy parallels the error model outlined in previous sections. This hierarchy assumes the presence of class xmsg , nominally provided by your compiler vendor. This is a class that is being considered for standardization by the Library Working Group of the C++ Standardization Committee X3J16 (document 92-0116). If your compiler does not come with versions of xmsg and xalloc , then the Tools.h++ classes RWxmsg and RWxalloc emulate them.
18 The flag RWDEBUG activates a set of PRECONDITION and POSTCONDITION clauses at the beginning and end of critical functions. The pre- and postconditions are implemented with “asserts”—a failure will cause the offending condition to be printed out, along with the file and line number where it occurred. RWPRECONDITION RWPOSTCONDITION Bertrand Meyer, in his landmark book “Object-oriented Software Construction” 1, suggests regarding functions as a “contract” between a caller and a callee.
18 Here’s a slightly more complicated example: template void List::insert(T* obj) { RWPRECONDITION( obj!= 0 ); head = new Link(head, obj); RWPOSTCONDITION( this->contains(obj) ); } The job of this function is to insert the object pointed to by the argument into a linked list of pointers to objects of type T. The only precondition for the function to work is that the pointer " obj" not be nil. If this condition is satisfied, then the function guarantees to successfully insert the object.
Implementation Notes 19 19.1 Copy on write Classes RWCString and RWTValVirtualArray use a technique called copy on write to minimize copying. This technique offers the advantage of easy-tounderstand value semantics with the speed of reference counting. When a RWCString constructor is initialized with another RWCString via the copy RWCString(const RWCString&); then the two strings will share the same data until one of them tries to write to it.
19 #include RWCString c(a);// 3 setGlobal(a);// Still only one copy of "kernel"! // 4 b += "s";// Now b has its own data: "kernels"// 5 } 1. The RWCString object " a" is where the actual allocation and initialization of the memory to hold the string " kernel " happens. 2–3 When objects " b" and "c" are created from it, they merely increment a reference count in the original data and return. At this point, there are three objects looking at the same piece of data.
19 On the surface, this approach is appealing because only one copy of the string need be made. Hence, calling setForeground() is efficient. But, the resulting semantics can be muddled: what if the string pointed to by foreground changes? Should the foreground color change? If so, how will class Simple know of the change? There is also a maintenance problem: before you can delete a "color" string, you must know if anyone is still pointing to it.
19 RWFile& RWvistream& RWFile& operator>>(RWFile&, operator>>(RWvistream&, operator>>(RWFile&, RWCollectable&); RWCollectable*&); RWCollectable*&); to save and restore the morphology of a class (i.e., the correct relationship between pointers). When working with RWCollectables , it is useful to understand how these functions work. Here is a brief description. When you call one of the l-shift (<<) operators for the first time for any collectable object, an IdentityDictionary is created internally.
19 class Tangle : public RWCollectable { public: RWDECLARE_COLLECTABLE(Tangle) Tangle* nextTangle; int someData; Tangle(Tangle* t = 0, int dat = 0) {nextTangle=t; someData=dat;} virtual void saveGuts(RWFile&) const; virtual void restoreGuts(RWFile&); }; void Tangle::saveGuts(RWFile& file) const { RWCollectable::saveGuts(file); // Save the base class file.
19 } } RWDEFINE_COLLECTABLE(Tangle, 100) main() { Tangle *head = 0, *head2 = 0; for (int i=0; i<10; i++) head = new Tangle(head,i); checkList(head); // Check the original list { RWFile file("junk.dat"); file << head; } RWFile file2("junk.dat"); file2 >> head2; checkList(head2); return 0; // Check the restored list } The class Tangle implements a (potentially) circularly linked list.
19 has already seen this instance before and, rather than call saveGuts() again, will just make a reference to the previously written link. This stops the series of recursive calls and the stack unwinds. Restoration of the chain is done in a similar manner. A call to RWFile& operator>>(RWFile&, RWCollectable*&); will either create a new object off the heap and return a pointer to it, return the address of a previously read object, or return the null pointer.
19 class A { }; main () { D d; fun(d); } // Which A ? There are two approaches to disambiguating the call to fun() . Either change it to: fun((B)d); or make A // We mean B's occurrence of A a virtual base class. The first approach is error prone — the user must know the details of the inheritance tree in order to make the proper cast.
19 19.4 Localizing messages Tools.h++ includes a facility for localizing messages, that is, formatting them in the native language of the user. This facility is used to localize exception messages, to be passed to xmsg (see Section 18.3, “Exception architecture,” on page 7 in Chapter 18, “Errors”).
19 19-10 104011 Tandem Computers Incorporated
Common Mistakes 20 We have made every effort to "tune" our libraries so as to minimize the chance of a programming error. Nevertheless, C++ is an extremely complex language with countless opportunities for making some very subtle mistakes. In writing this chapter, we went though our technical support documents to uncover the most common mistakes that our users were making. For those that could be prevented, we tried to rewrite the library to make them impossible.
20 For example: class MyObject : public RWCollectable { public: RWBooleanisEqual();// No "const" ! }; The compiler will treat this definition of isEqual() as completely independent of the isEqual() in the base class RWCollectable because it is missing a " const " modifier. Hence, if called through a pointer: MyObject obj; RWCollectable* c = &obj; c->isEqual();// RWCollectable::isEqual() will get called! 20.2 Iterators Immediately after construction, the position of a Tools.
20 20.3 Return type of operator>>() An extremely common mistake is to forget that the functions RWvistream& RWFile& operator>>(RWvistream&, RWCollectable*&); operator>>(RWFile&, RWCollectable*&); return their results off the heap . This can result in a memory leak: main() { RWCString* string = new RWCString;; RWFile file(“mydata.dat”); // WRONG: file >> string;// Memory leak! // RIGHT: delete string; file >> string; } 20.4 Include path Make sure that when you specify an include path to the Tools.
20 20.5 Match memory models and other qualifiers When it comes time to link your program to the Tools.h++ library, make sure that all qualifiers and memory models match. For example, if you compiled using the "compact" memory model, then make sure you are linking to a library compiled with the compact memory model. Failure to do so will result in the linker emitting mysterious "undefined external reference" errors. 20.
20 This program reads lines from a file specified on the command line and prints them to standard output. By using the full abilities of the RWCString class it could be greatly simplified: main(int argc, char* argv[]) { ifstream fstr(argv[1]); RWCString line; while (line.readLine(fstr)) { cout << line; } } There are countless other such examples. The point is, if it's looking awkward to you, it probably did to us.
20 20-6 104011 Tandem Computers Incorporated
Class Reference 21 C++ is still a young language; therefore there is no standard way to structure a reference manual for a class or group of classes. The reference is presented here as an alphabetical listing of classes with their member and global functions grouped in categories according to their general use. The categories are not a part of the C++ language, but do provide a way of organizing the many functions.
21 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 . Throughout this chapter, there are frequent references to "self." This should be understood to mean "* this .
21 RWBag RWBag | RWCollection | RWCollectable Synopsis typedef RWBag Bag; // Smalltalk typedef. #include 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 ).
21 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 .
21 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.
21 virtual void restoreGuts(RWvistream&); virtual void restoreGuts(RWFile&); virtual void saveGuts(RWvostream&) const; virtual void saveGuts(RWFile&) const; Inherited from class RWCollection .
21 RWBagIterator RWBagIterator | RWIterator Synopsis #include RWBag b; RWBagIterator it(b); Description Iterator for class RWBag , which allows sequential access to all the elements of RWBag . Note – Because a 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 times. Like all Tools.
21 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.
21 RWBench Synopsis #include (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.
21 Code Example 21-1 (2 of 3) TestRWCString() { } virtual void doLoop(unsigned long n); virtual void idleLoop(unsigned long n); virtual void what(ostream& s) const { s << "Tools.h++ hashing string \"" << cs << "\"\n"; } }; main(int argc, char* argv[]) { cout << "Testing string \"" << cs << "\"\n\n"; // Test Borland strings: TestBCCString bccstring; bccstring.parse(argc, argv); bccstring.go(); bccstring.report(cout); // Test RW Strings: TestRWCString rwstring; rwstring.parse(argc, argv); rwstring.
21 Code Example 21-1 (3 of 3) String string(cs);// Subtract out constructor time hashValueType h; while(n--){ /* No-op */ } } void TestRWCString::idleLoop(unsigned long n){ RWCString string(cs);// Subtract out constructor time unsigned h; while(n--){ /* No-op */ } } Program output: Testing string "A 22 character string." Borland C++ V3.0 Large memory model. Borland hashing string "A 22 character string.
21 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) .
21 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.
21 RWBinaryTree RWBinaryTree | RWCollection | RWCollectable Synopsis typedef RWBinaryTree SortedCollection; // Smalltalk typedef. #include RWBinaryTree bt; Description Class RWBinaryTree represents a group of ordered elements, internally sorted by the compareTo() function. Duplicates are allowed. An object stored by a RWBinaryTree must inherit abstract base class RWCollectable . Public constructors RWBinaryTree(); Construct an empty sorted collection.
21 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 balances the tree.
21 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() . virtual RWClassID isA() const; Redefined from class RWCollectable to return __RWBINARYTREE . virtual RWBoolean isEmpty() const; Redefined from class RWCollection .
21 RWBinaryTreeIterator RWBinaryTreeIterator | RWIterator Synopsis // Smalltalk typedef: typedef RWBinaryTreeIterator SortedCollectionIterator; #include 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() .
21 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 .
21 RWbistream RWbistream | RWvistream | RWvios Synopsis | ios #include RWbistream bstr(cin); Description // Construct a RWbistream, // using cin's streambuf Class RWbistream specializes the abstract base class RWvistream variables stored in binary format by RWbostream . to restore You can think of it as a binary veneer over an associated streambuf.
21 RWbistream(istream& str); Construct a RWbistream using the streambuf str . Public member functions associated with the istream virtual int get(); Redefined from class RWvistream . Get and return the next char input stream. Returns EOF if end of file is encountered. virtual RWvistream& get(char& c); Redefined from class RWvistream . Get the next char from the 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 .
21 virtual RWvistream& get(long* v, size_t N); Redefined from class RWvistream . Get a vector of long's and store then in the array beginning at v. If the restore is stopped prematurely, get stores whatever it can in v, and sets the failbit. virtual RWvistream& get(short* v, size_t N); Redefined from class RWvistream . Get a vector of short's and store then in the array beginning at v. If the restore is stopped prematurely, get stores whatever it can in v, and sets the failbit.
21 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 the latter, then the failbit of the stream will be set. In either case, the string will be terminated with a null byte. virtual RWvistream& operator>>(char& c); Redefined from class RWvistream .
21 virtual RWvistream& operator>>(unsigned long& l); Redefined from class RWvistream . Get the next unsigned long from the input stream and store it in l.
21 RWBitVec Synopsis #include 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 , whose lengths are fixed at compile time. Example #include #include main() { // Allocate a vector with 20 bits, set to TRUE: RWBitVec av(20, TRUE); av(2) = FALSE; av.clearBit(7); av.
21 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.
21 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 bitvec.h . If so, and if the index is out of range, then an exception of type RWBoundsErr will occur.
21 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.
21 void setBit(size_t i);// Set bit 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.
21 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.
21 RWbostream RWbostream | RWvostream | RWvios Synopsis | ios #include // Construct a 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 .
21 Example See RWbistream in. for an example of how the file "data.dat" might be read back #include #include main() { ofstream fstr("data.dat"); RWbostream bstr(fstr); int i = 5; float f = 22.1; double d = -0.05; bstr << i; bstr << f << d; Public constructors // Open an output file // Construct an RWbostream from it // Store an int in binary // Store a float & double} RWbostream(streambuf* s); Construct a RWbostream from the streambuf s .
21 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 .
21 virtual RWvostream& put(const char* p, size_t N); Redefined from class RWvostream . Store the vector of chars starting at p the output stream in binary. to 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.
21 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.
21 RWBTree RWBTree | RWCollection | RWCollectable Synopsis #include 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 .
21 Public member operators void Set self to a shallow copy of btr . operator=(const RWBTree& 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. 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.
21 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.
21 virtual void restoreGuts(RWvistream&); virtual void restoreGuts(RWFile&); virtual void saveGuts(RWvostream&) const; virtual void saveGuts(RWFile&) const; Inherited from class RWCollection .
21 RWBTreeDictionary RWBTreeDictionary | RWBTree | RWCollection | RWCollectable Synopsis #include RWBTreeDictionary a; Description Dictionary class implemented as a B-Tree , for the storage and retrieval of keyvalue 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.
21 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 .
21 virtual unsigned hash() const; Inherited from class RWCollectable . unsigned Inherited from class RWBTree . height() const; 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 Inherited from class RWBTree .
21 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 .
21 RWBTreeOnDisk Synopsis typedef long RWstoredValue; typedef int (*RWdiskTreeCompare)(const char*, const char*, size_t); #include #include 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.
21 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 rootLocation() . 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 also be set in the constructor.
21 Construct a B-Tree on disk. The parameters are as follows: f The file in which the B-Tree is to be managed. This is the only required parameter. nbuf The maximum number of nodes that can be cached in memory. omode Determines whether to force the creation of a new tree or whether to attempt to open an existing tree for update (the default). keylen The length of a key in bytes. Ignored when opening an existing tree. ignoreNull Controls whether to allow embedded nulls in keys.
21 The function yourApplyFunction cannot change the key. The value x can be anything and is passed through from the call to applyToKeyAndValue() . A possible exception that could occur is RWFileErr . void clear(); Removes all items from the collection. A possible exception that could occur is RWFileErr . RWBoolean contains(const char* ky) const; Returns TRUE if the tree contains a key that is equal to the string pointed to by ky, FALSE otherwise. A possible exception that could occur is RWFileErr .
21 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).
21 RWBufferedPageHeap RWBufferedPageHeap | RWVirtualPageHeap Synopsis #include (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.
21 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 Deallocates all internal buffers. ~RWBufferedPageHeap(); RWBoolean isValid(); Returns TRUE if self is in a valid state.
21 RRWCacheManager Synopsis #include RWFile f("file.dat"); RWCacheManager(&f, 100); Description // Construct a file // Cache 100 byte blocks to file.dat 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.
21 Public constructor RWCacheManager(RWFile* file, unsigned blocksz, unsigned mxblks = 10); Construct a cache for the RWFile pointed to by file . The length of the fixedsize blocks is given by blocksz . The number of cached blocks is given by mxblks . ~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 successful, FALSE otherwise.
21 RWCollectable Synopsis typedef RWCollectable Object; // Smalltalk typedef #include 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.
21 Note – 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.
21 virtual void saveGuts(RWvostream&) const; Write an object's state to an output stream. RWspace recursiveStoreSize() const; Returns the number of bytes required to store the object using the global operator RWFile& operator<<(RWFile&, const RWCollectables&); Recursively calls binaryStoreSize() , taking duplicate objects into account.
21 “Implementation Notes,” for a complete description. 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).
21 RWCollectableDate RWCollectableDate | | RWCollectable RWDate Synopsis typedef RWCollectableDate Date; // Smalltalk typedef #include 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.
21 virtual int compareTo(const RWCollectable* c) const; Redefined from class RWCollectable . Returns the results of calling RWDate::compareTo(c) . 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 .
21 RWCollectableInt RWCollectableInt | | RWCollectable RWInteger Synopsis typedef RWCollectableInt Integer; // Smalltalk typedef #include 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.
21 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 .
21 RWCollectableString RWCollectableString | | RWCollectable RWCString Synopsis typedef RWCollectableString String; // Smalltalk typedef #include /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 .
21 Public member functions virtual RWspace binaryStoreSize() const; Redefined from class RWCollectable . virtual int compareTo(const RWCollectable* c) const; Redefined from class RWCollectable . Calls RWCString::compareTo() with c as the argument and returns the results. This compares strings lexicographically. virtual unsigned hash() const; Redefined from class RWCollectable . Calls RWCString::hash() returns the results.
21 RWCollectableTime RWCollectableTime | | RWCollectable RWTime Synopsis typedef RWCollectableTime Time; // Smalltalk typedef #include 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.
21 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(c) . 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 .
21 RWCollection RWCollection | RWCollectable Synopsis #include typedef RWCollection Collection; Description // Smalltalk typedef 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.
21 Public member functions virtual Null definition (does nothing). ~RWCollection(); 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* c, void*); The function yourApplyFunction() can perform any operation on the item at address c that does not change the ordering of the collection.
21 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.
21 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 .
21 .RWCRegexp Synopsis #include RWCRegexp re(".*\.doc"); ".doc" Description // Matches filename with suffix 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.
21 2.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. 2.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. 2.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.
21 Example #include #include #include 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(RWCS); 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.
21 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.
21 RWCString Synopsis #include RWCString a; Description Class RWCString offers very powerful and convenient facilities for manipulating strings that are just as efficient as the familiar standard C 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).
21 Examples #include #include #include main() { RWCString a("There is no joy in Beantown."); RWCRegexp re("[A-Z][a-z]*town");// Any capitalized "town" a(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.
21 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 datum is owned by the RWCString and may not be deleted or changed.
21 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 exception of type RWBoundsErr will occur. char& operator()(size_t i); char operator()(size_t i) const; Return the i’th character. 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 .
21 RWCString& append(const RWCString& cstr, size_t N); Append the first N characters 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 characters the string can hold without resizing.
21 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 may (will!) become invalid. While the string is nullterminated, note that its length is still given by the member function length() . That is, it may contain embedded nulls.
21 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 . RWCString& insert(size_t pos, const char* cs); Insert a copy of the null-terminated string cs into self at position pos , thus expanding the string.
21 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(). 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. RWCString& prepend(const char* cs, size_t N, Prepend a copy of the character string cs to self.
21 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. 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.
21 void resize(size_t n); Changes the length of self to n, adding blanks or truncating as necessary. RWCSubString strip(stripType s = trailing, char c = ' '); Returns a substring of self where the character c has been stripped off the beginning, end, or both ends of the string.
21 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 characters. If more than mw characters 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 characters.
21 const RWCString&); 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.
21 Related global functions RWCString strXForm(const RWCString&); Returns the result of applying ::strxfrm() to the argument string, to allow quicker collation than RWCString::collate() . RWCString toLower(const RWCString& str); Returns a version of st r where all upper-case characters have been replaced with lower-case characters. Uses the standard C library function tolower() .
21 RWCSubString Synopsis Description #include RWCString s("test string"); s(6,3); // "tri" The class RWCSubString allows some subsection of a RWCString to be addressed by defining a starting position and an extent. For example the 7'th through the 11'th elements, inclusive, would have a starting position of 7 and an extent of 5.
21 Assignment operators void operator=(const RWCString&); Assignment to a 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. If self is the null substring, then the statement has no effect. void operator=(const char*) ; Assignment from a character string.
21 size_t length() const; Returns the extent (i.e., length) of the RWCSubString . RWBoolean Returns TRUE operator!() const; 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() .
21 RWCTokenizer Synopsis #include 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. Example #include #include
21 Public constructor RWCTokenizer(const RWCString& s); Construct a tokenizer to lex the string s. Public member function RWCSubString operator()(const char* s =" \t\n"); Advance to the next token and return it as a substring. The token are considered to be deliminated by any of the characters in s.
21 RWDate Synopsis Description #include RWDate a; // Construct today's date 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. RWDate 's can be converted to and from RWTime 's, and to and from the Standard C library type struct tm defined in .
21 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.
21 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.
21 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 the standard C library function strftime() . RWBoolean Returns TRUE if this RWDate between(const RWDate& a, const RWDate& b) const; is between a and b, inclusive.
21 unsigned firstDayOfMonth(unsigned month) const; Returns the day of the year (1-336) corresponding to the first day of the month month (1–12) in this RWDate ’s year. unsigned Returns a suitable hashing value. hash() const; RWBoolean Returns TRUE isValid() const; if this is a valid date, FALSE otherwise. RWBoolean Returns TRUE leap() const; if the year of this RWDate is a leap year. RWDate max(const RWDate& t) const; Returns the later date of self or t.
21 RWCString weekDayName(const RWLocale& = RWLocale::global()); 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 Returns the year of this date.
21 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 RWCString weekDayName(unsigned dayNum, const RWLocale& = RWLocale::global()); Returns the name of the day of the week dayNum (Monday = 1, ...
21 RWDate operator+(const RWDate& d, int s); RWDate operator+(int 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); Returns the number of days between d1 and d2 . RWDate operator-(const RWDate& d, int s); Returns the date s days in the past from d.
21 RWDiskPageHeap RWDiskPageHeap | RWBufferedPageHeap | RWVirtualPageHeap Synopsis #include 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. 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.
21 Code Example 21-2 (Continued) 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.
21 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 .
21 RWDlistCollectables RWDlistCollectables | | RWSequenceable RWDlist | | RWCollection RWSlist | RWCollectable Synopsis #include 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 .
21 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.
21 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 .
21 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 is, that have the address e).
21 RWDlistCollectablesIterator RWDlistCollectablesIterator | | RWIterator RWDlistIterator | RWSlistIterator Synopsis #include 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. Like all Tools.
21 void Moves the iterator back n Public member functions operator-=(size_t n); items. RWBoolean Returns TRUE atFirst() const; if the iterator is at the beginning of the list, otherwise FALSE ; RWBoolean Returns TRUE atLast() const; 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.
21 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.
21 RWFactory Synopsis typedef unsigned short RWClassID; typedef RWCollectable* (*sRWuserCreator)(); #include RWFactory* theFactory ; Description Class RWFactory can create an instance of a RWCollectable object, given a class ID. It does this by maintaining a table of class ID's and associated "creator function". A creator function has prototype: RWCollectable* aCreatorFunction (); This function should create an instance of a particular class.
21 delete b;// then the bag itself } Public constructors RWFactory(); Construct an RWFactory . 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 . 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.
21 RWFile Synopsis #include 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 .
21 RWBoolean Returns TRUE Error(); if a file I/O error has occurred. RWBoolean Returns TRUE Exists(); if the file exists and has read/write permission. RWBoolean Flush(); Perform any pending I/O operations. Returns TRUE const char* Returns the file name. if successful. GetName(); RWBoolean Returns TRUE IsEmpty(); if the file contains no data, FALSE RWBoolean Returns TRUE isValid() const if the file was successfully opened, FALSE otherwise. otherwise.
21 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 – You are responsible for declaring i storage before calling this function. and for allocating the necessary 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.
21 RWBoolean Write(float f); RWBoolean Write(double d); Writes the appropriate built-in type. Returns TRUE if the write is successful.
21 RWFileManager RWFileManager | RWFile Synopsis typedef long typedef unsigned long RWoffset; RWspace; // (typically) #include 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.
21 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 the offset of the last space allocated on this file. If no space has every been allocated, returns RWNIL .
21 RWHashDictionary RWHashDictionary | RWSet | RWHashTable | RWCollection | RWCollectable Synopsis typedef RWHashDictionary Dictionary; // Smalltalk typedef. #include RWHashDictionary a; Description A RWHashDictionary represents a group of unordered values, accessible by external keys. Duplicate keys are not allowed. Class RWHashDictionary is implemented as a hash table of associations of keys and values.
21 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.
21 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.
21 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.
21 RWHashDictionaryIterator RWHashDictionaryIterator | RWSetIterator | RWIterator Synopsis #include RWHashDictionary hd; RWHashDictionaryIterator Description iter(hd); 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 Tools.
21 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.
21 RWHashTable RWHashTable | RWCollection | RWCollectable Synopsis #include RWHashTable h; Description This class is a simple hash table for objects inheriting from RWCollectable . It uses chaining (as implemented by class RWSlistCollectables ) to resolve hash collisions. Duplicate objects are allowed. An object stored by RWHashTable must inherit from the abstract base class RWCollectable , with suitable definition for virtual functions hash() and isEqual() (see class RWCollectable ).
21 Example #include #include #include main() { RWHashTable table; table.insert(new Date(7, "July", 1990)); table.insert(new Date(1, "May", 1977)); table.insert(new Date(22, "Feb", 1983)); table.insert(new Date(2, "Aug", 1966)); cout << "Table contains " << table.entries() << " entries.\n"; Date key(22, "Feb", 1983); cout << "It does "; if (!table.
21 Publc operators void operator=(const RWHashTable& t); Assignment operator. Sets self as a shallow copy of t. Afterwards, the two tables will have the same number of buckets. Hence, the members need not be and will not be rehashed. RWBoolean operator==(const RWHashTable& t) const; Returns TRUE if self and t have the same number of elements and if for every key in self there is a corresponding key in t which isEqual.
21 virtual size_t Redefined from RWCollection . entries() const virtual RWCollectable* find(const RWCollectable*) const; Redefined from RWCollection . virtual unsigned Inherited from RWCollection . hash() const; virtual RWCollectable* insert(RWCollectable* a); Redefined from RWCollection . Returns a if successful, nil otherwise. virtual RWClassID Redefined from RWCollection isA() const; to return __RWHASHTABLE . virtual RWBoolean Redefined from RWCollection .
21 virtual void restoreGuts(RWvistream&); virtual void restoreGuts(RWFile&); virtual void saveGuts(RWvostream&) const; virtual void saveGuts(RWFile&) const; Inherited from class RWCollection .
21 RWHashTableIterator RWHashTableIterator | RWIterator Synopsis #include RWHashTable h; RWHashTableIterator it(h); Description Iterator for class RWHashTable , which allows sequential access to all the elements of RWHashTable . Note – Because a RWHashTable is unordered, elements are not accessed in any particular order. Like all Tools.h++ iterators, the "current item" is undefined immediately after construction—you must define it by using operator() or some other (valid) operation.
21 Public member functions 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. virtual RWCollectable* key() const; Redefined from class RWIterator . Returns the item at the current iterator position. RWCollectable* remove(); Remove the item at the current iterator position from the collection.
21 RWIdentityDictionary RWIdentityDictionary | RWHashDictionary | RWSet | RWCollection | RWCollectable Synopsis #include typedef RWIdentityDictionary IdentityDictionary; // Smalltalk typedef RWIdentityDictionary a; Description The class RWIdentityDictionary is implemented as a hash table, for the storage and retrieval of key-value pairs. Class RWIdentityDictionary is similar to class RWHashDictionary except that items are found by requiring that they be identical (i.e.
21 RWIdentitySet RWIdentitySet | RWSet | RWCollection | RWCollectable Synopsis #include typedef RWIdentitySet IdentitySet; // Smalltalk typedef RWIdentitySet a; Description The class RWIdentitySet is similar to class RWSet except that items are found by requiring that they be identical (i.e., have the same address) as the key, rather than being equal (i.e., test true for isEqual() ). The iterator for this class is RWSetIterator .
21 RWInteger Synopsis #include RWInteger i; Description Integer class. This class is useful as a base class for classes that use integers as keys in dictionaries, etc. Public constructors RWInteger(); Construct a RWInteger with value zero (0). RWInteger(int i); Construct a RWInteger with value i. Serves as a type conversion from int. Type conversion operator Type conversion to int.
21 RWvostream& operator<<(RWvostream&, const RWInteger& x); RWFile& operator<<(RWFile&, const RWInteger& x); Saves the RWInteger x to a virtual stream or RWFile , respectively. RWvistream& operator>>(RWvistream&, RWInteger& x); RWFile& operator>>(RWFile&, RWInteger& x); Restores an RWInteger into x from a virtual stream or RWFile , respectively, replacing the previous contents of x.
21 RWIterator Synopsis #include typedef RWIterator Iterator;// "Smalltalk" typedef Description Class RWIterator is an abstract base class for iterators used by the Smalltalklike collection classes. The class contains virtual functions for positioning and resetting the iterator. They are all pure virtual functions, meaning that deriving classes must supply a definition. The descriptions below are intended to be generic—all inheriting iterators generally follow the described pattern.
21 RWLocale Synopsis #include #include (Abstract base class) Description RWLocale is an abstract base class. It defines an interface for formatting dates (including day and month names), times, numbers (including digit grouping), and currency, to and from strings. Note that because it is an abstract base class, there is no way to actually enforce these goals—the description here is merely the model of how a class derived from RWLocale should act.
21 Public member functions virtual RWCString asString( long) const = 0; virtual RWCString asString(unsigned long) const = 0; Converts the number to a string (e.g., "3,456" ). virtual RWCString asString(double f, int precision = 6, RWBoolean showpoint = 0) const = 0; Converts the double f to a string. The variable precision is the number of digits to place after the decimal separator. If showpoint is TRUE , the decimal separator will appear regardless of the precision.
21 allowed. Returns TRUE for a valid integer, FALSE for an error. If it returns FALSE , the long* argument is untouched. All valid numeric strings are accepted; all others are rejected. The following are examples of valid integral strings in an English-speaking locale: “1” “ -02. “ “+ 1,234” “1234545” “1,234,567” Table 21-2 lists formatting characters used by strftime() . Examples are given (in parenthesis).
21 Table 21-2 (Continued) Format character Meaning Example x Date [uses tm::tm_yday in some locales] Feb 29 1984 X Time 14:34:56 y Year of the century, from 00 84 Y Year 1984 Z Time zone name [from tm::tm_isdst ] PST or PDT virtual RWBoolean stringToDate(const RWCString&, struct tm*) const = 0 ; Interprets the RWCString as a date, and extracts the month, day, and year components to the tm argument. It returns TRUE for a valid date, FALSE otherwise.
21 virtual RWBoolean stringToMoney(const RWCString&, double*, RWLocale::CurrSymbol=LOCAL) const = 0 ; Interprets the RWCString argument as a monetary value. The currency symbol, if any, is ignored. Negative values may be specified by the negation symbol or by enclosing parentheses. Digit group separators are optional; if present they are checked. Returns TRUE for a valid monetary value, FALSE for an error.
21 RWLocaleSnapshot RWLocaleSnapshot | RWLocale Synopsis #include #include /locale.h RWLocaleSnapshot ourLocale(""); formats // encapsulate user's Description The class RWLocaleSnapshot implements the RWLocale interface using Standard C library facilities. To use it, the program creates an RWLocaleSnapshot instance.
21 Code Example 21-3 (Continued) cout << locale.asString(1234567.6543) << endl; // Now get and print a date: cout << "enter a date: " << flush; RWDate date; cin >> date; if (date.isValid()) cout << date << endl; else cout << "bad date" << endl; return 0; } } Enumerations enum RWDateOrder { DMY, MDY, YDM, YMD } ; Public constructor RWLocaleSnapshot(const char* localeName = 0) ; Constructs an RWLocale object by extracting formats from the global locale environment.
21 virtual RWBoolean stringToMoney(const RWCString&, double* , RWLocale::CurrSymbol=LOCAL) const; Redefined from class RWLocale . These virtual functions follow the interface described under class RWLocale . They generally work by converting values to and from strings using the rules specified by the struct lconv values (see ) encapsulated in self.
21 RWModel Synopsis #include (abstract base class) Description This abstract base class has been designed to implement the “Model” leg of a Model-View-Controller architecture. A companion class, RWModelClient , supplies the “View” leg. It maintains a list of dependent RWModelClient objects. When member function changed(void*) is called, the list of dependents will be traversed, calling updateFrom(RWModel*, void*) for each one, with itself as the first argument.
21 Code Example 21-4 (Continued) void setTemperature(double t) { setting = t; changed(); } }; void Dial::updateFrom(RWModel* m, void*){ Thermostat* t = (Thermostat*)m; double temp = t-temperature(); // Redraw graphic. } Public constructor RWModel(); When called by the specializing class, sets up the internal ordered list of dependents. Public member functions void addDependent(RWModelClient* m); Adds the object pointed to by m to the list of dependents of self.
21 RWModelClient Synopsis #include (abstract base class) Description This abstract base class has been designed to implement the “View” leg of a Model-View-Controller architecture. Class RWModel , supplies the “Model” leg. See class RWModel for details. Public member function virtual void updateFrom(RWModel* p, void* d) = 0; Deriving classes should supply an appropriate definition for this pure virtual function.
21 RWOrdered RWOrdered | RWSequenceable | RWCollection | RWCollectable Synopsis #include RWOrdered a; Description Class RWOrdered represents a group of ordered items, accessible by an index number, but 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 RWOrdered must inherit from the abstract base class RWCollectable .
21 RWCollectable*& operator()(size_t i); Returns the i'th element in the collection. Bounds checking is enabled by defining the preprocessor directive RWBOUNDS_CHECK before including the header file ordcltn.h . In this case, if i is out of range, an exception of type RWBoundsErr will occur. The results of this function can be used as an lvalue. Public member functions virtual RWCollectable* append(RWCollectable*); Redefined from class RWSequenceable .
21 virtual RWCollectable* find(const RWCollectable* target) const; Redefined from class RWCollection . Returns the first item that isEqual to the item pointed to by target , or nil if no item was found. virtual RWCollectable* first() const; Redefined from class RWSequenceable . Returns the first item in the collection. virtual unsigned hash() const; Inherited from class RWCollectable . virtual size_t index(const RWCollectable*) const; Refined from class RWSequenceable .
21 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. void push(RWCollectable* c); This is an alternative implementation of a stack to class RWSlistCollectablesStack . The item pointed to by c is put at the end of the collection. RWCollectable* pop(); This is an alternative implementation of a stack to class RWSlistCollectablesStack .
21 RWOrderedIterator RWOrderedIterator | RWIterator Synopsis #include RWOrdered a; RWOrderedIterator iter(a); Description Iterator for class RWOrdered . Traverses the collection from the first to the last item. Like all Tools.h++ iterators, the "current item" is undefined immediately after construction—you must define it by using operator() or some other (valid) operation.
21 RWpistream RWpistream | RWvistream | RWvios Synopsis | istream #include RWpistream pstr(cin); cin's streambuf Description // Construct a RWpistream, using Class RWpistream specializes the abstract base class RWvistream variables stored in a portable ASCII format by RWpostream .
21 Example See RWpostream program. for an example of how to create an input stream for this #include main() { // Construct a RWpistream to use standard input RWpistream pstr(cin); int i; float f; double d; char string[80]; pstr >> i; // Restore an int that was stored in binary pstr >> f >> d; // Restore a float & double pstr.getString(string, 80); // Restore a character string } Public constructors RWpistream(streambuf* s); Initialize a RWpistream from the streambuf s .
21 virtual RWvistream& get(char* v, size_t N); Redefined from class RWvistream . Get a vector of char's and store then in the array beginning at v. If the restore is stopped prematurely, get stores whatever it can in v, and sets the failbit. Note – The vector is treated as a vector of numbers, not characters. If you wish to restore a character string, use function getString(char*, size_t) . virtual RWvistream& get(wchar_t* v, size_t N); Redefined from class RWvistream .
21 virtual RWvistream& get(unsigned char* v, size_t N); Redefined from class RWvistream . Get a vector of unsigned char's and store then in the array beginning at v. If the restore is stopped prematurely, get stores whatever it can in v, and sets the failbit. Note – The vector is treated as a vector of numbers, not characters. If you wish to restore a character string, use function getString(char*, size_t) . virtual RWvistream& get(unsigned short* v, size_t N); Redefined from class RWvistream .
21 latter, then the failbit of the stream will be set. In either case, the string will be terminated with a null byte. If the input stream has been corrupted, then an exception of type RWExternalErr will be thrown. virtual RWvistream& operator>>(char& c); Redefined from class RWvistream . Get the next character from the input stream and store it in c. virtual RWvistream& operator>>(double& d); Redefined from class RWvistream . Get the next double from the input stream and store it in d.
21 RWpostream RWpostream | RWvostream | RWvios Synopsis | ostream #include // Construct a RWpostream, using cout's streambuf: RWBostream pstr(cout); Description Class RWpostream specializes the abstract base class RWvostream to store variables in a portable (printable) ASCII format. The results can be restored by using its counterpart RWpistream .
21 Note – Variables should not be separated with whitespace. Such whitespace would be interpreted literally and would have to be read back in as a character string. RWpostream can be interrogated as to the stream state using member functions good() , bad() , eof() , etc. Example See RWpistream for an example of how to read back in the results of this program. The symbol " o " is intended to represent a control-G, or bell. #include
21 Public member functions virtual RWvostream& operator<<(const char* s); Redefined from class RWvostream . Store the character string starting at s to the output stream using a portable format. 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 using a portable format. The character string is expected to be null terminated.
21 virtual RWvostream& operator<<(unsigned int i); Redefined from class RWvostream . Store the unsigned int i to the output stream using a portable format. virtual RWvostream& operator<<(long l); Redefined from class RWvostream . Store the long l to the output stream using a portable format. virtual RWvostream& operator<<(unsigned long l); Redefined from class RWvostream . Store the unsigned long l to the output stream using a portable format.
21 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 using a portable format. The characters should be treated as literal numbers (i.e., not as a character string). 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 using a portable format.
21 RWSequenceable RWSequenceable | RWCollection | RWCollectable Synopsis #include typedef RWSequenceable SequenceableCollection; // Smalltalk typedef Description Class RWSequenceable is an abstract base class for collections that can be accessed via an index. It inherits class RWCollection as a public base class and adds a few extra virtual functions. This documentation only describes these extra functions.
21 void insertAt(size_t indx, RWCollectable* 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 RWBoundsErr will be thrown. virtual RWCollectable* last() const = 0; Returns the last item in the collection. RWCollectable* prepend(RWCollectable*) = 0; Adds the item to the beginning of the collection and returns it.
21 RWSet RWSet | RWHashTable | RWCollection | RWCollectable Synopsis typedef RWSet Set; #include // Smalltalk typedef. RWSet h; Description Class RWSet represents a group of unordered elements, not accessible by an external key, where duplicates are not allowed. It corresponds to the Smalltalk class Set . An object stored by RWSet must inherit abstract base class RWCollectable , with suitable definition for virtual functions hash() and isEqual() (see class RWCollectable ).
21 Public member operators void operator=(const RWSet& h); Assignment operator. Makes a shallow copy of the collection h. RWBoolean operator==(const RWSet& h); Returns TRUE if self and h have the same number of elements and if for every key in self there is a corresponding key in h which isEqual. RWBoolean operator!=(const RWSet& h); Returns the negation of operator==() , above.
21 virtual RWCollectable* find(const RWCollectable* target) const; Redefined from class RWCollection . Returns the item in self which isEqual to the item pointed to by target 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 . Adds c to the collection and returns it.
21 virtual void restoreGuts(RWvistream&); virtual void restoreGuts(RWFile&); virtual void saveGuts(RWvostream&) const; virtual void saveGuts(RWFile&) const; Inherited from class RWCollection .
21 RWSetIterator RWSetIterator | RWHashTableIterator | RWIterator Synopsis #include RWSet h; RWSetIterator it(h); Description Iterator for class RWSet , which allows sequential access to all the elements of RWSet . Note – Because a RWSet particular order. is unordered, elements are not accessed in any Like all Tools.h++ iterators, the "current item" is undefined immediately after construction—you must define it by using operator() or some other (valid) operation.
21 Public member functions virtual RWCollectable* findNext(const RWCollectable* target); Inherited from RWHashTableIterator . virtual RWCollectable* key() const; Inherited from RWHashTableIterator . RWCollectable* remove(); Inherited from RWHashTableIterator . RWCollectable* removeNext(const RWCollectable*); Inherited from RWHashTableIterator . virtual void reset(); Inherited from RWHashTableIterator .
21 RWSlistCollectables RWSlistCollectables | | RWSequenceable RWSlist | RWCollection | RWCollectable Synopsis // Smalltalk typedef: typedef RWSlistCollectables LinkedList; #include RWSlistCollectables a; Description Class RWSlistCollectables represents a group of ordered elements, without keyed access. Duplicates are allowed. The ordering of elements is determined externally, by the order of insertion and removal.
21 Public member functions virtual RWCollectable* append(RWCollectable*); Redefined from RWSequenceable . Inserts the item at the end of the collection and returns it. Returns nil if the insertion was unsuccessful. virtual void apply(RWapplyCollectable ap, void*) Redefined from class RWCollection . This function has been redefined to apply the user-defined function pointed to by ap to each member of the collection, in order, from first to last.
21 virtual RWCollectable* find(const RWCollectable* target) const; Redefined from class RWCollection . The first item that matches target returned, or nil if no item was found. is 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.
21 virtual RWCollectable* last() const; Redefined from class RWSequenceable . Returns the value at the end of the collection. 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 is, that have the address e).
21 RWSlistCollectablesIterator RWSlistCollectablesIterator | | RWIterator RWSlistIterator Synopsis // Smalltalk typedef. typedef RWSlistCollectablesIterator LinkedListIterator; #include RWSlistCollectables sc; RWSlistCollectablesIterator sci(sc); Description Iterator for class RWSlistCollectables . Traverses the linked-list from the first to last item. Like all Tools.
21 RWBoolean Returns TRUE atLast() const; 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.
21 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.
21 RWSlistCollectablesQueue RWSlistCollectablesQueue | RWSlistCollectables | | RWSequenceable RWSlist | RWCollection | RWCollectable Synopsis // Smalltalk typedef: typedef RWSlistCollectablesQueue Queue; #include RWSlistCollectablesQueue a; Description Class RWSlistCollectablesQueue represents a restricted interface to class RWSlistCollectables to implement a first in first out (FIFO) queue.
21 RWSlistCollectablesQueue(const RWSlistCollectablesQueue & q); Copy constructor. A shallow copy of the queue q is made. Public member operators void Public member functions virtual void operator=(const RWSlistCollectablesQueue & q); Assignment operator. A shallow copy of the queue q is made. apply(RWapplyCollectable ap, void*) Inherited from class RWSlistCollectables . virtual RWCollectable* append(RWCollectable*); Inherited from class RWSlistCollectables . Adds an element to the end of the queue.
21 virtual RWCollectable* insert(RWCollectable* c); Redefined from class RWSlistCollectables to call append() . virtual RWClassID isA() const; Redefined from class RWCollectable to return __RWSLISTCOLLECTABLESQUEUE . virtual RWBoolean isEmpty() const; Inherited from class RWSlistCollectables . virtual RWCollectable* last() const; Inherited from class RWSlistCollectables . Returns the last item in the queue (the most recently inserted item).
21 RWSlistCollectablesStack RWSlistCollectablesStack | RWSlistCollectables | | RWSequenceable RWSlist | RWCollection | RWCollectable Synopsis // Smalltalk typedef: typedef RWSlistCollectablesStackStack; #include RWSlistCollectablesStack a ; Description Class RWSlistCollectablesStack represents a restricted interface to class RWSlistCollectables to implement a last in first out (LIFO) stack.
21 Assignment operator void Public member functions virtual void apply(RWapplyCollectable ap, void*) virtual RWspace binaryStoreSize() const; virtual void clear(); Inherited from class RWSlistCollectables . operator=(const RWSlistCollectablesStack& s); Assignment operator. A shallow copy of the stack s is made. virtual void virtual RWBoolean clearAndDestroy(); contains(const RWCollectable* target) const; Inherited from class RWCollection .
21 virtual RWCollectable* remove(const RWCollectable*); Redefined from class RWSlistCollectables . Calls pop() . The argument is ignored. RWCollectable* pop(); Removes and returns the item at the top of the stack, or returns nil if the stack is empty. void push(RWCollectable*); Adds an item to the top of the stack. RWCollectable* top() const; Returns the item at the top of the stack or nil if the stack is empty.
21 RWSortedVector RWSortedVector | RWOrdered | RWSequenceable | RWCollection | RWCollectable Synopsis #include RWSortedVector a; Description Class RWSortedVector represents a group of ordered items, internally sorted by the compareTo() function and accessible by an index number. Duplicates are allowed. An object stored by RWSortedVector must inherit from the abstract base class RWCollectable . An insertion sort is used to maintain the vector in sorted order.
21 Example #include #include #include main() { RWSortedVector sv; sv.insert(new RWCollectableString("dog")); sv.insert(new RWCollectableString("cat")); sv.insert(new RWCollectableString("fish")); RWSortedVectorIterator next(sv); RWCollectableString* item; while( item = (RWCollectableString*)next() ) cout << *item << endl; sv.
21 const RWCollectable* operator()(size_t i); Returns the i'th element in the collection. Bounds checking is enabled by defining the preprocessor directive RWBOUNDS_CHECK before including the header file sortvec.h . In this case, if i is out of range, an exception of type RWBoundsErr will be thrown. This function cannot be used as an lvalue. Public member functions virtual void apply(RWapplyCollectable ap, void* x); Inherited from class RWOrdered .
21 virtual unsigned hash() const; Inherited from class RWCollectable . virtual size_t index(const RWCollectable*) const; Redefined from class RWOrdered. Performs a binary search to return the index of the first item that compares equal to the target item, or RW_NPOS if no such item can be found. virtual RWCollectable* insert(RWCollectable* c); Redefined from class RWOrdered .
21 RWTime Synopsis #include RWTime a; // Construct with current time Class RWTime represents a time, stored as the number of seconds since 00:00:00 January 1901 UTC. See “Setting the time zone” on page 1 in Chapter 7, “Using Class RWTime,” for how to set the time zone for your compiler. Description ! Caution – Failure to do this may result in UTC (GMT) times being wrong. Output formatting is now done using an RWLocale formats according to U.S. conventions. object.
21 RWTime(unsigned hour, unsigned minute, unsigned second = 0, const RWZone& zone = RWZone::local()); Constructs a time with today’s date, and the specified hour, minute, and second, relative to the time zone zone , which defaults to local time. RWTime(const RWDate& date, unsigned hour = 0, unsigned minute = 0, unsigned second = 0, const RWZone& = RWZone::local()); Constructs a time for a given date, hour, minute, and second, relative to the time zone zone , which defaults to local time.
21 RWTime operator--(); Prefix decrement operator. Subtract one second from self, then return the results. RWTime operator++(int); Postfix increment operator. Add one second to self, returning the initial value. RWTime operator--(int); Postfix decrement operator. Subtract one second from self, returning the initial value. RWTime& operator+=(long s); Add s seconds to self, returning self. RWTime& Subtract s Public member functions operator-=(long s); seconds from self, returning self.
21 void extract(struct tm*, const RWZone& = RWZone::local()) const; Fills all members of the struct tm argument, adjusted to the time zone specified by the RWZone argument. If the time is invalid, the struct tm members are all set to -1. Note – the encoding of struct tm members is different from that used in RWTime and RWDate functions. unsigned Returns a suitable hashing value.
21 unsigned second() const; Returns the second; local time or UTC (GMT). unsigned long seconds() const; Returns the number of seconds since 00:00:00 January 1, 1901 UTC. Static public member functions static RWTime beginDST(unsigned year, const RWZone& zone = RWZone::local()); Return the start of Daylight Savings Time (DST) for the given year , in the given time zone. Returns an “invalid time” if DST is not observed in that year and zone.
21 RWBoolean Returns TRUE if t1 operator>(const RWTime& t1, const RWTime& t2); is greater than t2 . if t1 operator>=(const RWTime& t1, const RWTime& t2); is greater than or equal to t2 . if t1 operator==(const RWTime& t1, const RWTime& t2); is equal to t2 . if t1 operator!=(const RWTime& t1, const RWTime& t2); is not equal to t2 .
21 RWTimer Synopsis #include RWTimer timer; Description This class can measure elapsed CPU (user) time. The timer has two states: running and stopped. The timer measures the total amount of time spent in the "running" state since it was either constructed or reset. The timer is put into the "running" state by calling member function start() . It is put into the "stopped" state by calling stop() .
21 Program output: 5.054945 Public constructor RWTimer(); Constructs a new timer. The timer will not start running until start() called. is double elapsedTime() const; Returns the amount of (CPU) time that has accumulated while the timer was in the running state. void Resets (and stops) the timer. reset(); void start(); Puts the timer in the "running" state. Time accumulates while in this state. void stop(); Puts the timer in the "stopped" state. Time will not accumulate while in this state.
21 RWVirtualPageHeap Synopsis #include (Abstract base class ) Description This is an abstract base class representing an abstract page heap of fixed sized pages. The following describes the model by which specializing classes of this class are expected to work. You allocate a page off the abstract heap by calling member function allocate() which will return a memory "handle", an object of type RWHandle . This handle logically represents the page.
21 Example This example illustrates adding N nodes to a linked list. In this linked list, a "pointer" to the next node is actually a handle. #include struct Node { int key; RWHandle }; next; RWHandle head = 0; void addNodes(RWVirtualPageHeap& heap, unsigned N) { for (unsigned i=0; ikey = i; newNode->next = head; head = h; heap.dirty(h); heap.
21 Public pure virtual functions virtual RWHandle allocate() = 0 Allocates a page off the abstract heap and returns a handle for it. If the specializing class is unable to honor the request, then it should return a zero handle. virtual void deallocate(RWHandle h) = 0; Dallocate the page associated with handle h. It is not an error to deallocate a zero handle. virtual void dirty(RWHandle h) = 0; Declare the page associated with handle h to be "dirty". That is, it has changed since it was last locked.
21 RWvistream RWvistream | RWvios Synopsis #include Description Class RWvistream is an abstract base class. It provides an interface for format-independent retrieval of primitives and arrays of primitives. Its counterpart, RWvostream , provides a complementary interface for the storage of these variables. Because the interface of RWvistream and RWvostream is independent of formatting, the user of these classes need not be concerned with how variables will actually be stored or restored.
21 Example #include void restoreStuff( RWvistream& str) { int i; double d; char string[80]; str >> i; // Restore an int str >> d; // Restore a double // Restore a character string, up to 80 characters long: str.getString(string, sizeof(string)); if(str.fail()) cerr << "Oh, oh, bad news.\n"; } Public member functions virtual int get() = 0; Get and return the next char from the input stream, returning its value. Returns EOF if end of file is encountered.
21 Note – The vector is treated as a vector of numbers, not characters. If you wish to restore a character string, use function getString(wchar_t*, size_t) . virtual RWvistream& get(double* v, size_t N) = 0; Get a vector of double's and store then in the array beginning at v. If the restore is stopped prematurely, get stores whatever it can in v, and sets the failbit. virtual RWvistream& get(float* v, size_t N) = 0; Get a vector of float's and store then in the array beginning at v.
21 virtual RWvistream& get(unsigned int* v, size_t N) = 0; Get a vector of unsigned int's and store then in the array beginning at v. If the restore is stopped prematurely, get stores whatever it can in v, and sets the failbit. virtual RWvistream& get(unsigned long* v, size_t N) = 0 ; Get a vector of unsigned long's and store then in the array beginning at v. If the restore is stopped prematurely, get stores whatever it can in v, and sets the failbit.
21 virtual RWvistream& operator>>(short& s) = 0; Get the next short from the input stream and store it in s. virtual RWvistream& operator>>(unsigned char& c) = 0; Get the next unsigned char from the input stream and store it in c. virtual RWvistream& operator>>(unsigned short& s) = 0; Get the next unsigned short from the input stream and store it in s. virtual RWvistream& operator>>(unsigned int& i) = 0; Get the next unsigned int from the input stream and store it in i.
21 RWvostream RWvostream | RWv ios Synopsis #include Description Class RWvostream is an abstract base class. It provides an interface for format-independent storage of primitives and arrays of primitives. Its counterpart, RWvistream , provides a complementary interface for the retrieval of these variables. Because the interface of RWvistream and RWvostream is independent of formatting, the user of these classes need not be concerned with how variables will actually be stored or restored.
21 of its representation on the target machine. By contrast, member functions get() and put() should treat the character as a literal number, whose value is to be preserved. See also class RWpostream . Example #include void storeStuff( RWvostream& str) { int i = 5; double d = 22.5; char string[] = "A string with \t tabs and a newline\n"; str << i;// Store an int str << d;// Store a double str << string;// Store a string if(str.fail()) cerr << "Oh, oh, bad news.
21 virtual RWvostream& Store the unsigned char c Note – c operator<<(unsigned char c) = 0; to the output stream. is treated as a character, not a number. virtual RWvostream& operator<<(double d) = 0; Store the double d to the output stream. virtual RWvostream& operator<<(float f) = 0; Store the float f to the output stream. virtual RWvostream& operator<<(int i) = 0; Store the int i to the output stream. virtual RWvostream& operator<<(unsigned int i) = 0; Store the unsigned int i to the output stream.
21 virtual RWvostream& put(const wchar_t* p, size_t N) = 0; Store the vector of wide chars starting at p to the output stream. The chars should be treated as literal numbers (i.e., not as a character string). virtual RWvostream& put(const unsigned char* p, size_t N) = 0; Store the vector of unsigned chars starting at p to the output stream. The chars should be treated as literal numbers (i.e., not as a character string).
21 RWWString Synopsis #include RWWString a; Description Class RWWString offers very powerful and convenient facilities for manipulating wide character strings. This string class manipulates wide characters of the Standard C type wchar_t . These characters are generally two or four bytes, and can be used to encode richer code sets than the classic "char" type. Because wchar_t characters are all the same size, indexing is fast.
21 Example #include #include main() { RWWString a(L"There is no joy in Beantown."); a.subString(L"Beantown") = L"Redmond"; cout << a << endl; return 0; } Program output: There is no joy in Redmond. Enumerations enum RWWString::caseCompare { exact, ignoreCase } ; Used to specify whether comparisons, searches, and hashing functions should use case sensitive ( exact ) or case-insensitive (ignoreCase ) semantics.
21 RWWString(RWSize_T ic) Creates a string of length zero (the null string). The strings capacity (that is, the size it can grow to without resizing) is given by the parameter ic . RWWString(const RWWString& str) ; Copy constructor. The created string will copy str ’s data. RWWString(const RWWSubString& ss) ; Conversion from sub-string. The created string will copy the substring represented by ss . RWWString(char c); Constructs a string containing the single character c.
21 previously returned may (will!) become invalid. While the string is nullterminated, note that its length is still given by the member function length() . That is, it may contain embedded nulls. Assignment operators RWWString& operator=(const char* cs); Assignment operator. Copies the null-terminated character string pointed to by cs into self. Returns a reference to self. RWWString& operator=(const RWWString& str) ; Assignment operator. The string will copy str ’s data. Returns a reference to self.
21 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 be thrown. Public member functions RWWString& append(const wchar_t* cs); Append a copy of the null-terminated character string pointed to by cs to self. Returns a reference to self. RWWString& append(const wchar_t* cs, size_t N) ; Append a copy of the character string cs to self.
21 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 RWWString::exact or RWCString::ignoreCase. RWBoolean contains(const RWWString& cs, caseCompare = exact) const; RWBoolean contains(const wchar_t* str, caseCompare = exact) const ; Pattern matching. Returns TRUE if cs occurs in self.
21 const; Pattern matching. Starting with index i, searches for the first occurrence of the first patlen characters 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. RWWString& insert(size_t pos, const wchar_t* cs); Insert a copy of the null-terminated string cs into self at position pos . Returns a reference to self.
21 RWWString& prepend(const wchar_t* cs, size_t N,); Prepend a copy of the character string cs to self. Exactly N characters 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. RWWString& prepend(const RWWString& str); Prepends a copy of the string str to self. Returns a reference to self.
21 delimiter is removed from the input stream but is not stored. The input stream is treated as a sequence of multibyte characters, each of which is converted to a wide character (using the Standard C library function mbtowc() ) before storing. Null characters are treated the same as other characters. istream& readToken(istream& s); Whitespace is skipped before saving characters.
21 RWWString& replace(size_t pos, size_t N1, const RWWString& str, size_t N2); Replaces N1 characters or to the end of string (whichever comes first) starting at position pos with a copy of the first N2 characters, or the length of str (whichever is less), from str . Returns a reference to self. void resize(size_t n); Changes the length of self, adding blanks (i.e., W' ' ) or truncating as necessary.
21 void toUpper() ; Changes all lower-case letters in self to upper-case. Uses the C library function towupper() . Static public member functions static size_t initialCapacity(size_t ic = 15); Sets the minimum initial capacity of an RWWString , and returns the old value. The initial setting is 15 characters. 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.
21 wchar_t* ); operator> (const wchar_t*, const RWWString&); RWBoolean operator> (const RWWString&, const RWWString&); RWBoolean operator<= (const RWWString&, const wchar_t* ); RWBoolean operator<= (const wchar_t*, const RWWString&); RWBoolean operator<= (const RWWString&, const RWWString&); RWBoolean operator>= (const RWWString&, const wchar_t* ); RWBoolean operator>= (const wchar_t*, const RWWString&); RWBoolean operator>= (const RWWString&, const RWWString&); Comparisons are done lexicographically, byte
21 RWvistream& operator>>(RWvistream&, RWWString& str); RWFile& operator>>(RWFile&, RWWString& str); Restores a wide character string into str from a virtual stream or RWFile , respectively, replacing the previous contents of str . Related global functions RWWString strXForm(const RWWString&); Returns a string transformed by ::wsxfrm() , to allow quicker collation than RWWString::collate() .
21 RWWSubString Synopsis #include RWWString s(L"test string"); s(6,3); // "tri" Description The class RWWSubString allows some subsection of a RWWString to be addressed by defining a starting position and an extent. For example the 7'th through the 11'th elements, inclusive, would have a starting position of 7 and an extent of 5.
21 Assignment operators void operator=(const RWWString&); Assignment to a RWWString . The statements: RWWString a; RWWString 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. If self is the null substring, then the statement has no effect. void operator=(const wchar_t*); Assignment from a wide character string.
21 size_t length() const; Returns the extent (i.e., length) of the RWWSubString . RWBoolean Returns TRUE operator!() const; if this is a null substring. size_t start() const; Returns the starting element of the RWWSubString . void toLower(); Changes all upper-case letters in self to lower-case. Uses the C library function towlower() . void toUpper(); Changes all lower-case letters in self to upper-case. Uses the C library function towupper() .
21 RWWTokenizer Synopsis #include RWWString str("a string of tokens", RWWString::ascii); RWWTokenizer(str); // Lex the above string Description Class RWWTokenizer 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 C library function wstok () which has the unfortunate side effect of changing the string being tokenized. Example #include #include
21 Public member function RWWSubString operator()(const wchar_t* s =L" \t\n"); Advance to the next token and return it as a substring. The tokens are considered to be deliminated by any of the characters in s.
21 RWXDRistream RWXDRistream | | RWvistream RWios | RWvios Synopsis #include XDR xdr; xdrstdio_create(&xdr, stdin, XDR_DECODE); RWXDRistream rw_xdr(&xdr); Description Class RWXDRistream is a portable input stream based on XDR routines. Class RWXDRistream encapsulates a portion of the XDR library routines that are used for external data representation. XDR routines allow programmers to describe arbitrary data structures in a machine-independent fashion.
21 The library that supports XDR routines must be linked in. The name of this library is not standard. #include “rw/xdrstrea.h” #include “rw/rstream.h” #include
21 virtual RWvistream& get(unsigned char& c); Redefined from class RWvistream . Gets the next unsigned character from the XDR input stream and stores it in c. If the operation fails, it sets the failbit. virtual RWvistream& get(char* v, size_t N); Redefined from class RWvistream . Gets a vector of characters from the XDR input stream and stores them in v. If the operation fails, it sets the failbit. virtual RWvistream& get(unsigned char* v, size_t N); Redefined from class RWvistream .
21 virtual RWvistream& get(wchar_t* v, size_t N); Redefined from class RWvistream . Gets a vector of wide characters from the XDR input stream and stores them in v. If the operation fails, it sets the failbit. virtual RWvistream& getString(char* s, size_t maxlen); Redefined from class RWvistream . Restores a character string from the XDR input stream and stores them in the array starting at s. The function stops reading at the end of the string or after maxlen-1 characters, whichever comes first.
21 virtual RWvistream& operator>>(unsigned int& i); Redefined from class RWvistream . Gets the next unsigned integer from the XDR input stream and stores it in i. If the operation fails, it sets the failbit. virtual RWvistream& operator>>(unsigned long& l); Redefined from class RWvistream. Gets the next unsigned long from the XDR input stream and stores it in l. If the operation fails, it sets the failbit. virtual RWvistream& operator>>(unsigned short& s); Redefined from class RWvistream .
21 RWXDRostream RWXDRostream | | RWvostream RWios | RWv ios Synopsis #include XDR xdr; xdrstdio_create(&xdr, stdout, XDR_ENCODE); RWXDRostream rw_xdr(&xdr); Description Class RWXDRostream is a portable output stream based on XDR routines. Class RWXDRostream encapsulates a portion of the XDR library routines that are used for external data representation. XDR routines allow programmers to describe arbitrary data structures in a machine-independent fashion.
21 Example The example that follows is a “writer” program that encodes an XDR structure onto a FILE stream. The example for class RWXDRistream is the “reader” program that decodes the XDR structures into a machine representation for a data type. The library that supports XDR routines must be linked in. The name of this library is not standard. #include “rw/xdrstrea.h” #include “rw/rstream.h” #include
21 virtual RWvostream& operator<<(unsigned char c); Redefined from class RWvostream . Store the unsigned character c to the output stream using the XDR format. Note that c is treated as a character, not a number. virtual RWvostream& operator<<(double d); Redefined from class RWvostream . Store the double d to the output stream using the XDR format. virtual RWvostream& operator<<(float f); Redefined from class RWvostream . Store the float f to the output stream using the XDR format.
21 virtual RWvostream& put(wchar_t wc); Redefined from class RWvostream . Store the wide character wc to the output stream using the XDR format. If the operation fails, it sets the failbit. virtual RWvostream& put(const char* p, size_t N); Redefined from class RWvostream . Store the vector of characters starting at p to the output stream using the XDR format. If the operation fails, it sets the failbit. virtual RWvostream& put(const wchar_t* p, size_t N); Redefined from class RWvostream .
21 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 using the XDR format. If the operation fails, it sets the failbit. 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 using the XDR format. If the operation fails, it sets the failbit.
21 RWZone Synopsis #include #include (abstract base class) Description RWZone is an abstract base class. It defines an interface for time zone issues such as whether or not daylight savings time is in use, the names and offsets from UTC (also known as GMT) for both standard and daylight savings times, and the start and stop dates for daylight savings time, if used.
21 Enumerations enum DstRule { NoDST, NoAm, WeEu }; Used by the static member function dstRule() , described below, and by constructors for classes derived from RWZone . enum StdZone { NewZealand = -12, Japan, Kazakh, Ukraine, Greenwich, Greenland, USCentral, Yukon, }; CarolineIslands, China, Pakistan, Nile, Azores, Atlantic, USMountain, Hawaii, MarianaIslands, Java, CaspianSea, Europe, Oscar, USEastern, USPacific, Bering StdZone is provided to name the standard time zones.
21 virtual void getBeginDaylight(struct tm*) const = 0; virtual void getEndDaylight (struct tm*) const = 0; Return with the struct tm argument set to the (local) time that daylight savings time begins, or ends, for the year indicated by the tm_year member passed in. If daylight savings time is not observed, the struct tm members are all set to a negative value. Note – that in the southern hemisphere, daylight savings time ends at an earlier date than it begins.
21 RWZoneSimple RWZoneSimple | RWZone Synopsis #include #include RWZoneSimple myZone(USCentral) ; Description RWZoneSimple is an implementation of the abstract interface defined by class RWZone . It implements a simple daylight savings time rule sufficient to represent all historical U.S. conventions and many European and Asian conventions. It is table-driven and depends on parameters given by class RWDaylightRule .
21 Likewise for Japan: RWZone::local(new RWZoneSimple(RWZone::Japan, RWZone::NoDST)) ; For France: RWZone::local(new RWZoneSimple(RWZone::Europe, RWZone::WeEu)) ; Here are the rules used internally for the RWZone::NoAm values of RWZone::DstRule: and RWZone::WeEu // last Sun in Apr to last in Oct: const RWDaylightRuleusRuleAuld = { 0, 0000, 1, { 3, 4, 0, 120 }, { 9, 0, 120 } }; // first Sun in Apr to last in Oct const RWDaylightRuleusRule67 = { &usRuleAuld, 1967, 1, { 3, 0, 0, 120 }, { 9, 4, 120 } }; //
21 Given these definitions, RWZone::local(new RWZoneSimple(RWZone::USCentral, &usRuleLate)) ; is equivalent to the first example given above and repeated here: RWZone::local(new RWZoneSimple(RWZone::USCentral)) ; Daylight savings time systems that cannot be represented with RWDaylightRule and RWZoneSimple must be modeled by deriving from RWZone and implementing its virtual functions.
21 RWZoneSimple(RWZone::StdZone zone, const RWDaylightRule* rule); Constructs an RWZoneSimple instance in which offsets and names are specified by the StdZone argument. Daylight Savings Time is computed according to the rule argument, if non-zero; otherwise, DST is not observed.
21 21-240 104011 Tandem Computers Incorporated
Part 3— Templates
Templates 22 RWTBitVec Synopsis #include RWTBitVec<22> // A 22 bit long vector RWTBitVec is a parameterized bit vector of fixed length size. Unlike class RWBitVec , its length cannot be changed at run time. Its advantage of RWBitVec is its smaller size, and one less level of indirection, resulting in a slight speed advantage. Bits are numbered from 0 through size– 1, inclusive. The copy constructor and assignment operator use copy semantics.
22 Public constructor RWTBitVec< size >(); Constructs an instance with all bits set to FALSE. RWTBitVec< size >(RWBoolean val); Constructs an instance with all bits set to val . Assignment operators RWTBitVec& operator=(const RWTBitVec& v); Sets self to a copy of v. RWTBitVec& operator=(RWBoolean val); Sets all bits in self to the value val . RWTBitVec& operator&=(const RWTBitVec& v); RWTBitVec& operator^=(const RWTBitVec& v) RWTBitVec& operator|=(const RWTBitVec& v) Logical assignments.
22 RWBoolean operator!=(const RWTBitVec& v) const; Returns TRUE if any bit of self is not set to the same value as the corresponding bit in v. Otherwise, returns FALSE . 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 two lines are equivalent, although clearBit(size_t) is slightly smaller and faster than using operator()(size_t) : a(i) = FALSE; a.
22 Related global functions RWTBitVec operator&(const RWTBitVec& v1, const RWTBitVec& v2); RWTBitVec operator^(const RWTBitVec& v1, const RWTBitVec& v2); RWTBitVec operator|(const RWTBitVec& v1, const RWTBitVec& v2); Return the logical AND, XOR, and OR, respectively, of vectors v1 and v2 .
22 RWTIsvDlist Synopsis #include RWTIsvDlist list; Class RWTIsvDlist is a class that implements intrusive singly-linked lists. Descripton An intrusive list is one where the member of the list must inherit from a common base class, in this case RWIsvDlink . The advantage of such a list is that memory and space requirements are kept to a minimum. The disadvantage is that the inheritance hierarchy is inflexible, making it slightly more difficult to use with an existing class.
22 Example #include #include #include struct Symbol : public RWIsvDlink { char name[10]; Symbol( const char* cs) { strncpy(name, cs, sizeof(name)); name[9] = '\0'; } }; void printem(Symbol* s, void*) { cout << s->name << endl; } main(){ RWTIsvDlist list; list.insert( new Symbol("one") ); list.insert( new Symbol("two") ); list.prepend( new Symbol("zero") ); list.apply(printem, 0); list.
22 void apply(void (*applyFun)(T*, void*), void* d); Calls the function pointed to by applyFun to every item in the collection. This must have the prototype: void yourFun(T* item, void* d); The item will be passed in as argument item. Client data may be passed through as parameter d. T* at(size_t i) const; Returns the item at index i. 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.
22 T* find(RWBoolean (*testFun)(const T*, void*), void* d) const; Returns the first item in the list for which the user-defined "tester" function pointed to by testFun returns TRUE . If there is no such item, then returns nil. The tester function must have the prototype: RWBoolean yourTester (const T* item, void* d); For each item in the list this function will be called with the item as the first argument. Client data may be passed through as parameter d.
22 size_t occurrencesOf(RWBoolean (*testFun)(const T*, void*), void* d) const; Traverses the list and returns the number of times for which the user-defined "tester" function pointed to by testFun returned TRUE . The tester function must have the prototype: RWBoolean yourTester (const T* item, void* d); For each item in the list this function will be called with the item as the first argument. Client data may be passed through as parameter d.
22 T* removeLast(); Removes and returns the last item in the list, or nil if there are no items in the list. T* removeReference(const T* a); Removes and returns the item with address a, or nil if there is no such item.
22 RWTIsvDlistIterator Synopsis #include RWTIsvDlist list; RWTIsvDlistIterator iterator(list); Description Iterator for class RWTIsvDlist , allowing sequential access to all the elements of a doubly-linked parameterized intrusive list. Elements are accessed in order, in either direction. Like all Tools.h++ iterators, the "current item" is undefined immediately after construction—you must define it by using operator() or some other (valid) operation.
22 Public member functions RWTIsvDlist* container() const; Returns a pointer to the collection over which this iterator is iterating. T* findNext(RWBoolean (*testFun)(const T*, void*), void*); Advances the iterator to the first link for which the tester function pointed to by testFun returns TRUE and returns it, or nil if there is no such link.
22 RWTIsvSlist Synopsis #include RWTIsvSlist list; Class RWTIsvSlist is a class that implements intrusive singly-linked lists. Descripton An intrusive list is one where the member of the list must inherit from a common base class, in this case RWIsvSlink . The advantage of such a list is that memory and space requirements are kept to a minimum. The disadvantage is that the inheritance hierarchy is inflexible, making it slightly more difficult to use with an existing class.
22 Example #include #include #include struct Symbol : public RWIsvSlink { char name[10]; Symbol( const char* cs) { strncpy(name, cs, sizeof(name)); name[9] = '\0'; } }; void printem(Symbol* s, void*) { cout << s-name << endl; } main(){ RWTIsvSlist list; list.insert( new Symbol("one") ); list.insert( new Symbol("two") ); list.prepend( new Symbol("zero") ); list.apply(printem, 0); list.
22 void apply(void (*applyFun)(T*, void*), void* d); Calls the function pointed to by applyFun to every item in the collection. This must have the prototype: void yourFun(T* item, void* d); The item will be passed in as argument item. Client data may be passed through as parameter d. T* at(size_t i) const; Returns the item at index i. 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.
22 T* find(RWBoolean (*testFun)(const T*, void*), void* d) const; Returns the first item in the list for which the user-defined "tester" function pointed to by testFun returns TRUE . If there is no such item, then returns nil. The tester function must have the prototype: RWBoolean yourTester (const T* item, void* d); For each item in the list this function will be called with the item as the first argument. Client data may be passed through as parameter d.
22 size_t occurrencesOf(RWBoolean (*testFun)(const T*, void*), void* d) const; Traverses the list and returns the number of times for which the user-defined "tester" function pointed to by testFun returned TRUE . The tester function must have the prototype: RWBoolean yourTester (const T* item, void* d); For each item in the list this function will be called with the item as the first argument. Client data may be passed through as parameter d.
22 T* removeLast(); Removes and returns the last item in the list, or nil if there are no items in the list. This function is relatively slow because removing the last link in a singlylinked list necessitates access to the next-to-the-last link, requiring the whole list to be searched. T* removeReference(const T* a); Removes and returns the link with address a. The link must be in the list. In a singly-linked list this function is not very efficient.
22 RWTIsvSlistIterator Synopsis #include RWTIsvSlist list; RWTIsvSlistIterator iterator(list); Description Iterator for class RWTIsvSlist , allowing sequential access to all the elements of a singly-linked parameterized intrusive list. Elements are accessed in order, from first to last. Like all Tools.h++ iterators, the "current item" is undefined immediately after construction—you must define it by using operator() or some other (valid) operation.
22 Public member functions RWTIsvSlist* container() const; Returns a pointer to the collection over which this iterator is iterating. T* findNext(RWBoolean (*testFun)(const T*, void*), void*); Advances the iterator to the first link for which the tester function pointed to by testFun returns TRUE and returns it, or nil if there is no such link.
22 RWTPtrDlist Synopsis #include RWTPtrDlist list; Description This class maintains a collection of pointers to type T, implemented as a doubly linked list. This is a pointer based list: pointers to objects are copied in and out of the links that make up the list. Parameter T represents the type of object to be inserted into the list, either a class or built in type. The class T must have: • Example well-defined equality semantics (T::operator==(const T&)).
22 Code Example 22-1 (2 of 2) if (this!=&dog) { delete name; name = new char[strlen(dog.name)+1]; strcpy(name, dog.name); } } // Define an equality test operator: int operator==(const Dog& dog) const { return strcmp(name, dog.name)==0; } friend ostream& operator<<(ostream& str, const Dog& dog){ str << dog.name; return str;} }; main() { RWTPtrDlist terriers; terriers.insert(new Dog("Cairn Terrier")); terriers.insert(new Dog("Irish Terrier")); terriers.
22 Program output: The list does contain a Schnauzer Cairn Terrier Fox Terrier Irish Terrier Schnauzer Public constructors RWTPtrDlist(); Constructs an empty list. RWTPtrDlist(const RWTPtrDlist& c); Constructs a new doubly-linked list as a shallow copy of c. After construction, pointers will be shared between the two collections. Public operators RWTPtrDlist& operator=(const RWTPtrDlist& c); Sets self to a shallow copy of c. Afterwards, pointers will be shared between the two collections.
22 T*& at(size_t i); T* at(size_t i) const; Returns a pointer to the i'th value in the list. The first variant can be used as an l-value, 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 from the collection. void clearAndDestroy(); Removes all items from the collection and calls their destructors.
22 RWBoolean yourTester (T*, void* d); This function will be called for each item in the list, with a pointer to the item as the first argument. Client data may be passed through as parameter d. T* first() const; Returns a pointer to the first item in the list. The behavior is undefined if the list is empty. T* get(); Returns a pointer to the first item in the list and removes the item. The behavior is undefined if the list is empty.
22 size_t occurrencesOf(T* a) const; Returns the number of objects in the list that are equal to the object pointed to by a. Equality is measured by the class-defined equality operator for type T. size_t occurrencesOf(RWBoolean (*testFun)(T*, void*), void* d) const; Returns the number of objects in the list for which the user-defined "tester" function pointed to by testFun returns TRUE .
22 Removes all objects for which the user-defined tester function pointed to by testFun returns TRUE . Returns the number of objects removed. The tester function must have the prototype: RWBoolean yourTester (T*, void* d); This function will be called for each item in the list, with a pointer to the item as the first argument. Client data may be passed through as parameter d. T* removeAt(size_t i); Removes the object at index i and returns a pointer to it.
22 RWTPtrDlistIterator Synopsis #include RWTPtrDlist list; RWTPtrDlistIterator iterator(list); Description Iterator for class RWTPtrDlist , allowing sequential access to all the elements of a doubly-linked parameterized list. Elements are accessed in order, in either direction. Like all Tools.h++ iterators, the "current item" is undefined immediately after construction—you must define it by using operator() or some other (valid) operation.
22 RWBoolean operator-=(size_t n); Retreats the iterator n positions and returns TRUE . When the beginning of the collection is reached, returns FALSE and the position of the iterator will be undefined. T* operator()(); Advances the iterator to the next item and returns a pointer to it. When the end of the collection is reached, returns nil and the position of the iterator will be undefined.
22 T* removeNext(T* a); Advances the iterator to the first element that is equal to the object pointed to by a, then removes and returns it. Afterwards, the iterator will be positioned at the element immediately before the removed element. Returns nil if unsuccessful in which case the position of the iterator is undefined. Equality is measured by the class-defined equality operator for type T.
22 RWTPtrHashDictionary Synopsis #include unsigned hashFun(const K&); RWTPtrHashDictionary dictionary(hashFun); Description RWTPtrHashDictionary is a dictionary of keys of type K and values of type V, implemented using a hash table. While duplicates of values are allowed, duplicates of keys are not. It is a pointer based collection: pointers to the keys and values are copied in and out of the hash buckets.
22 must be searched linearly. The number of buckets can be changed by calling member function resize() . This is relatively expensive because all of the keys must be rehashed. If you wish for this to be done automatically, then you can subclass from this class and implement your own special insert() and remove() functions which perform a resize() as necessary. Example Code Example 22-2 #include #include #include #include
22 Program output: April 12, 1975 Public constructors RWTPtrHashDictionary(unsigned (*hashKey)(const K&), size_t buckets = RWDEFAULT_CAPACITY); Constructs an empty hash dictionary. The first argument is a pointer to a userdefined hashing function for items of type K (the key). The table will initally have buckets buckets although this can be changed with member function resize() . RWTPtrHashDictionary(const RWTPtrHashDictionary& c ); Constructs a new hash dictionary as a shallow copy of c.
22 This function will be called for each key value pair in the dictionary, with a pointer to the key as the first argument and a reference to a pointer to the value as the second argument. The key should not be changed or touched. A new value can be substituted, or the old value can be changed. Client data may be passed through as parameter d. void clear(); Removes all key value pairs from the collection.
22 RWBoolean Returns TRUE isEmpty() const; if the dictionary has no items in it, FALSE otherwise. K* remove(K* key); Removes the key and value pair where the key is equal to the key pointed to by key . Returns the key or nil if no match was found. Equality is measured by the class-defined equality operator for type K. void resize(size_t N); Changes the number of buckets to N. This will result in all of the keys being rehashed.
22 RWTPtrHashDictionaryIterator Synopsis #include unsigned hashFun(const K&); RWTPtrHashDictionary dictionary(hashFun); RWTPtrHashDictionaryIterator iterator(dictionary); Description Iterator for class RWTPtrHashDictionary , allowing sequential access to all keys and values of a parameterized hash dictionary. Elements are not accessed in any particular order. Like all Tools.
22 Public member functions RWTPtrHashDictionary* container() const; Returns a pointer to the collection over which this iterator is iterating. K* key() const; Returns a pointer to the key at the iterator's current position. The results are undefined if the iterator is no longer valid. void reset(); Resets the iterator to the state it had immediately after construction. void reset(RWTPtrHashDictionary& c); Resets the iterator to iterate over the collection c.
22 RWTPtrHashSet RWTPtrHashSet | RWTPtrHashTable Synopsis #include unsigned hashFun(const T&); RWTPtrHashSet(hashFun) set; Description RWTPtrHashSet is a derived class of RWTPtrHashTable where the insert() function has been overridden to accept only one item of a given value. Hence, each item in the collection will have a unique value. As with class RWTPtrHashTable , you must supply a hashing function to the constructor.
22 Code Example 22-3 (Continued) cout << set.entries() << endl;// Prints "3" return 0; } Program output: 3 Public constructor RWTPtrHashSet(unsigned (*hashFun)(const T&), size_t buckets = RWDEFAULT_CAPACITY); Constructs an empty hashing set. The first argument is a pointer to a userdefined hashing function for items of type T. The table will initally have buckets buckets although this can be changed with member function resize() .
22 RWBoolean isEmpty() const; Inherited from class RWTPtrHashTable . size_t occurrencesOf(T* a) const; Inherited from class RWTPtrHashTable . T* remove(T* a); Inherited from class RWTPtrHashTable . size_t removeAll(T* a); Inherited from class RWTPtrHashTable . void resize(size_t N); Inherited from class RWTPtrHashTable .
22 RWTPtrHashTable Synopsis #include unsigned hashFun(const T&); RWTPtrHashTable table(hashFun); Description This class implements a parameterized hash table of types T. It uses chaining to resolve hash collisions. Duplicates are allowed. It is a pointer based collection: pointers to objects are copied in and out of the hash buckets. Parameter T represents the type of object to be inserted into the table, either a class or built in type.
22 Example #include #include #include unsigned hashIt(const RWCString& str) {return str.hash();} main() { RWTPtrHashTable table(hashIt); table.insert(new table.insert(new table.insert(new table.insert(new RWCString("Alabama")); RWCString("Pennsylvania")); RWCString("Oregon")); RWCString("Montana")); RWCString key("Oregon"); cout << "The table " << (table.contains(&key) ? "does " : "does not ") << "contain Oregon\n"; table.
22 Constructs an empty hash table. The first argument is a pointer to a userdefined hashing function for items of type T. The table will initally have buckets buckets although this can be changed with member function resize() . RWTPtrHashTable(const RWTPtrHashTable& c); Constructs a new hash table as a shallow copy of c. After construction, pointers will be shared between the two collections. The new object will have the same number of buckets as c. Hence, the keys will not be rehashed.
22 T* find(T* a) const; Returns a pointer to the object which is equal to the object pointed to by a, or nil if no such object can be found. Equality is measured by the class-defined equality operator for type T. void Adds the object pointed to by a RWBoolean Returns TRUE insert(T* a); to the collection. isEmpty() const; if the collection has no items in it, FALSE otherwise. size_t occurrencesOf(T* a) const; Returns the number of objects in the collection which are equal to the object pointed to by a.
22 RWTPtrHashTableIterator Synopsis #include RWTPtrHashTable table; RWTPtrHashTableIterator iterator(table); Description Iterator for class RWTPtrHashTable , allowing sequential access to all the elements of a hash table. Elements are not accessed in any particular order. Like all Tools.h++ iterators, the "current item" is undefined immediately after construction—you must define it by using operator() or some other (valid) operation.
22 void reset(); Resets the iterator to the state it had immediately after construction. void reset(RWTPtrHashTable& c); Resets the iterator to iterate over the collection c.
22 RWTPtrOrderedVector Synopsis #include RWTPtrOrderedVector ordvec; Description RWTPtrOrderedVector is a pointer-based ordered collection. That is, the items in the collection have a meaningful ordered relationship with respect to one another and can be accessed by an index number. The order is set by the order of insertion. Duplicates are allowed.
22 Program output: 5 entries 22 5.3 -102.5 15 5.3 Public constructors RWTPtrOrderedVector(size_t capac=RWDEFAULT_CAPACITY); Creates an empty ordered vector with capacity capac . Should the number of items exceed this value, the vector will be resized automatically. RWTPtrOrderedVector(const RWTPtrOrderedVector& c); Constructs a new ordered vector as a shallow copy of c. After construction, pointers will be shared between the two collections.
22 T*& at(size_t i); T* at(size_t i) const; Returns a pointer to the i'th value in the vector. The first variant can be used as an l-value, 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 from the collection. void clearAndDestroy(); Removes all items from the collection and calls their destructors.
22 void insertAt(size_t i, T* a); Adds the object pointed to by a at the index position i. The item previously at position i is moved to i+1 , etc. The collection will be resized automatically if this causes the number of items to exceed the capacity. The index i must be between 0 and the number of items in the vector or an exception of type TOOL_INDEX will occur. RWBoolean Returns TRUE isEmpty() const; if there are no items in the collection, FALSE otherwise.
22 T* removeFirst(); Removes the first item in the collection and returns a pointer to it. An exception of type TOOL_INDEX will be thrown if the list is empty. T* removeLast(); Removes the last item in the collection and returns a pointer to it. An exception of type TOOL_INDEX will be thrown if the list is empty. void resize(size_t N); Changes the capacity of the collection to N. Note – The number of objects in the collection does not change, just the capacity.
22 RWTPtrSlist Synopsis #include RWTPtrSlist list; Description This class maintains a collection of pointers to type T, implemented as a singlylinked list. This is a pointer based list: pointers to objects are copied in and out of the links that make up the list. Parameter T represents the type of object to be inserted into the list, either a class or built in type. The class T must have: • Example well-defined equality semantics ( T::operator==(const T&) ).
22 Code Example 22-4 (Continued) delete d; } return 0; } Program output: Found date June 2, 1952 April 1, 1990 March 30, 1946 June 2, 1952 Public constructors RWTPtrSlist(); Construct an empty list. RWTPtrSlist(const RWTPtrSlist& c); Constructs a new singly-linked list as a shallow copy of c. After construction, pointers will be shared between the two collections. Public operators RWTPtrSlist& operator=(const RWTPtrSlist& c); Sets self to a shallow copy of c.
22 void yourFun(T* a, void* d); This function will be called for each item in the list, with a pointer to the item as the first argument. Client data may be passed through as parameter d. T*& at(size_t i); T* at(size_t i) const; Returns a pointer to the i'th value in the list. The first variant can be used as an l-value, 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.
22 T* find(RWBoolean (*testFun)(T*, void*), void* d,) const; Returns a pointer to the first object encountered for which the user-defined tester function pointed to by testFun returns TRUE , or nil if no such object can be found. The tester function must have the prototype: RWBoolean yourTester (T*, void* d); This function will be called for each item in the list, with a pointer to the item as the first argument. Client data may be passed through as parameter d.
22 T* last() const; Returns a pointer to the last item in the list. The behavior is undefined if the list is empty. size_t occurrencesOf(T* a) const; Returns the number of objects in the list that are equal to the object pointed to by a. Equality is measured by the class-defined equality operator for type T. size_t occurrencesOf(RWBoolean (*testFun)(T*, void*), void* d) const; Returns the number of objects in the list for which the user-defined "tester" function pointed to by testFun returns TRUE .
22 size_t removeAll(RWBoolean (*testFun)(T*, void*), void* d); Removes all objects for which the user-defined tester function pointed to by testFun returns TRUE . Returns the number of objects removed. The tester function must have the prototype: RWBoolean yourTester (T*, void* d); This function will be called for each item in the list, with a pointer to the item as the first argument. Client data may be passed through as parameter d.
22 RWTPtrSlistIterator Synopsis #include RWTPtrSlist list; RWTPtrSlistIterator iterator(list); Description Iterator for class RWTPtrSlist , allowing sequential access to all the elements of a singly-linked parameterized list. Elements are accessed in order, from first to last. Like all Tools.h++ iterators, the "current item" is undefined immediately after construction—you must define it by using operator() or some other (valid) operation.
22 Public member functions RWTPtrSlist* container() const; Returns a pointer to the collection over which this iterator is iterating. T* findNext(T* a); Advances the iterator to the first element that is equal to the object pointed to by a and returns a pointer to it. If no item is found, returns nil and the position of the iterator will be undefined. Equality is measured by the classdefined equality operator for type T.
22 T* removeNext(RWBoolean (*testFun)(T*, void*), void*); Advances the iterator to the first element for which the tester function pointed to by testFun returns TRUE , then removes and returns it. Afterwards, the iterator will be positioned at the element immediately before the removed element. Returns nil if unsuccessful in which case the position of the iterator is undefined. void reset(); Resets the iterator to the state it had immediately after construction.
22 RWTPtrSortedVector Synopsis #include RWTPtrSortedVector sortvec; Description RWTPtrSortedVector is a pointer-based ordered collection. That is, the items in the collection have a meaningful ordered relationship with respect to each other and can be accessed by an index number. In the case of RWTPtrSortedVector , objects are inserted such that objects "less than" themselves are before the object, objects "greater than" themselves after the object. An insertion sort is used.
22 Code Example 22-5 (Continued) cout << *vec[i] << endl; vec.clearAndDestroy(); return 0; } Program output: May 14, 1990 June 2, 1991 August 9, 1991 August 10, 1991 September 1, 1991 September 1, 1991 Public constructor RWTPtrSortedVector(size_t capac = RWDEFAULT_CAPACITY); Create an empty sorted vector with an initial capacity equal to capac . The vector will be automatically resized should the number of items exceed this amount.
22 T*& operator[](size_t i); T* operator[](size_t i) const; Returns a pointer to the i'th value in the vector. The first variant can be used as an l-value, 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. Public member functions T*& at(size_t i); T* at(size_t i) const; Returns a pointer to the i'th value in the vector. The first variant can be used as an l-value, the second cannot.
22 size_t index(T* a) const; Performs a binary search, returning the index of the first object that is equal to the object pointed to by a, or RW_NPOS if there is no such object. Equality is measured by the class-defined equality operator for type T. void insert(T* a); Performs a binary search, inserting the object pointed to by a after all items that compare less than or equal to it, but before all items that do not. "Less Than" is measured by the class-defined '<' operator for type T.
22 T* removeFirst(); Removes the first item in the collection and returns a pointer to it. An exception of type TOOL_INDEX will be thrown if the list is empty. T* removeLast(); Removes the last item in the collection and returns a pointer to it. An exception of type TOOL_INDEX will be thrown if the list is empty. void resize(size_t N); Changes the capacity of the collection to N. Note – The number of objects in the collection does not change, just the capacity.
22 RWTPtrVector Synopsis #include RWTPtrVector vec; Descripton Class RWTPtrVector is a simple parameterized vector of pointers to objects of type T. It is most useful when you know precisely how many objects have to be held in the collection. If the intention is to "insert" an unknown number of objects into a collection, then class RWTPtrOrderedVector may be a better choice. The class T can be of any type. Example #include #include
22 Program output: March March March March March March March Public constructors 16, 17, 18, 19, 20, 21, 22, 1992 1992 1992 1992 1992 1992 1992 RWTPtrVector(); Constructs an empty vector of length zero. RWTPtrVector(size_t n); Constructs a vector of length n. The initial values of the elements is undefined. Hence, they can (and probably will) be garbage. RWTPtrVector(size_t n, T* ival); Constructs a vector of length n, with each element initialized to the value ival .
22 T*& operator[](size_t i); T* operator[](size_t i) const; Returns a pointer to the i'th value in the vector. The first variant can be used as an l-value, the second cannot. The index i must be between zero and the length of the vector, less one, or an exception of type TOOL_INDEX will be thrown. Public member functions T* const * data() const; Returns a pointer to the raw data of the vector. Should be used with care. size_t Returns the length of the vector.
22 RWTQueue Synopsis #include RWTQueue queue; Description This class represents a parameterized queue. Not only can the type of object inserted into the queue be parameterized, but also the implementation. Parameter T represents the type of object in the queue, either a class or built in type. The class T must have: • well-defined copy semantics ( T::T(const T&) or equiv.); • well-defined assignment semantics ( T::operator=(const T&) or equiv.
22 Example In this example a queue of RWCStrings , implemented as a singly-linked list, is exercised. #include #include #include #include main() { RWTQueue > queue; queue.insert("one"); // Type conversion occurs queue.insert("two"); queue.insert("three"); while (!queue.isEmpty()) cout << queue.
22 T get(); Returns and removes the first item in the queue (the item least recently inserted into the queue). RWBoolean Returns TRUE isEmpty() const; if there are no items in the queue, otherwise FALSE . void Inserts the item a insert(const T& a); at the end of the queue. T last() const; Returns, but does not remove, the last item in the queue (the item most recently inserted into the queue).
22 RWTStack Synopsis #include RWTStack stack; Description This class maintains a stack of values. Not only can the type of object inserted onto the stack be parameterized, but also the implementation of the stack. Parameter T represents the type of object in the stack, either a class or built in type. The class T must have: • well-defined copy semantics ( T::T(const T&) or equiv.); • well-defined assignment semantics ( T::operator=(const T&) or equiv.
22 Example In this example a stack of ints, implemented as an ordered vector, is exercised. #include #include #include main() { RWTStack > stack; stack.push(1); stack.push(5); stack.push(6); while (!stack.isEmpty()) cout << stack.pop() << endl; return 0; } Program output: 6 5 1 Public constructor RWTStack(); Constructs an empty stack of objects of type T, implemented using class C.
22 T pop(); Pop (remove and return) the item at the top of the stack. If there are no items on the stack then an exception of type TOOL_INDEX will occur. T top() const; Returns (but does not remove) the item at the top of the stack.
22 RWTValDlist Synopsis #include RWTValDlist list; Description This class maintains a collection of values, implemented as a doubly linked list. This is a value based list: objects are copied in and out of the links that make up the list. Unlike intrusive lists (see class RWTIsvDlist ), the objects need not inherit from a link class.
22 Code Example 22-6 (2 of 2) Dog(const Dog& dog) { name = new char[strlen(dog.name)+1]; strcpy(name, dog.name); } // Define an assignment operator: void operator=(const Dog& dog) { if (this!=&dog) { delete name; name = new char[strlen(dog.name)+1]; strcpy(name, dog.name); } } // Define an equality test operator: int operator==(const Dog& dog) const { return strcmp(name, dog.name)==0; } friend ostream& operator<<(ostream& str, Dog& dog){ str << dog.
22 Program output: The list does contain a Schnauzer Cairn Terrier Fox Terrier Irish Terrier Schnauzer Public constructors RWTValDlist(); Construct an empty list. RWTValDlist(const RWTValDlist& list); Construct a copy of the list list . Depending on the nature of the copy constructor of T, this could be relatively expensive because every item in the list must be copied. Public operators RWTValDlist& operator=(const RWTValDlist& list); Sets self to a copy of the list list .
22 Client data may be passed through as parameter d. T& at(size_t i); Returns a reference to the item at index i. The results can be used as an lvalue. An exception of type TOOL_INDEX will be thrown if i is not a valid index. Valid indices are from zero to the number of items in the list less one. T at(size_t i) const; Returns a copy of the item at index i. The results cannot be used as an lvalue. An exception of type TOOL_INDEX will be thrown if i is not a valid index.
22 function pointed to by testFun returns TRUE and puts a copy of the matching object into k. Returns FALSE otherwise and does not touch k. The tester function must have the prototype: RWBoolean yourTester (const T&, void* d); For each item in the list this function will be called with the item as the first argument. Client data may be passed through as parameter d. If you do not need a copy of the found object, use contains() instead.
22 T last() const; Returns (but does not remove) the last item in the list. The behavior is undefined if the list is empty. size_t occurrencesOf(const T& a) const; Returns the number of objects in the list that are equal to the object a. Equality is measured by the class-defined equality operator. size_t occurrencesOf(RWBoolean (*testFun) (const T&, void*),void* d) const; Returns the number of objects in the list for which the user-defined "tester" function pointed to by testFun returns TRUE .
22 size_t removeAll(RWBoolean (*testFun) (const T&, void*), void* d); Removes all objects for which the user-defined tester function pointed to by testFun returns TRUE . Returns the number of objects removed. The tester function must have the prototype: RWBoolean yourTester (const T&, void* d); For each item in the list this function will be called with the item as the first argument. Client data may be passed through as parameter d. T removeAt(size_t i); Removes and returns the object at index i.
22 RWTValDlistIterator Synopsis #include RWTValDlist list; RWTValDlistIterator iterator(list); Description Iterator for class RWTValDlist , allowing sequential access to all the elements of a doubly-linked parameterized list. Elements are accessed in order, in either direction. Like all Tools.h++ iterators, the "current item" is undefined immediately after construction—you must define it by using operator() or some other (valid) operation.
22 RWBoolean operator-=(size_t n); Retreats the iterator n positions and returns TRUE . When the beginning of the collection is reached, returns FALSE and the position of the iterator will be undefined. RWBoolean operator()(); Advances the iterator to the next item. Returns TRUE valid, FALSE otherwise. Public member functions if the new position is RWTValDlist* container() const; Returns a pointer to the collection over which this iterator is iterating.
22 RWBoolean removeNext(const T& a); Advances the iterator to the first element that is equal to a and removes it. Returns TRUE if successful, FALSE otherwise. Equality is measured by the class-defined equality operator for type T. Afterwards, if successful, the iterator will be positioned at the element immediately before the removed element.
22 RWTValHashDictionary Synopsis #include unsigned hashFun(const K&); RWTValHashDictionary dictionary(hashFun); Description RWTValHashDictionary is a dictionary of keys of type K and values of type V, implemented using a hash table. While duplicates of values are allowed, duplicates of keys are not. It is a value based collection: keys and values are copied in and out of the hash buckets.
22 member function resize() . This is an expensive proposition because not only must all the items be copied into the new buckets, but all of the keys must be rehashed. If you wish this to be done automatically, then you can subclass from this class and implement your own special insert() and remove() functions which perform a resize() as necessary. Example #include #include #include #include unsigned hashString(const RWCString& str){return str.
22 defined hashing function for items of type K (the key). The table will initally have buckets buckets although this can be changed with member function resize() . RWTValHashDictionary(const RWTValHashDictionary& dict); Copy constructor. Constructs a new hash dictionary as a copy of dict . The new dictionary will have the same number of buckets as the old table. Hence, although the keys and values must be copied into the new table, the keys will not be rehashed.
22 RWBoolean contains(const K& key) const; Returns TRUE if the dictionary contains a key which is equal to key. Returns FALSE otherwise. Equality is measured by the class-defined equality operator for class K. size_t entries() const; Returns the number of key-value pairs currently in the dictionary. RWBoolean find(const K& key, K& retKey) const; Returns TRUE if the dictionary contains a key which is equal to key and puts the matching key into retKey . Returns FALSE otherwise and leaves retKey untouched.
22 void resize(size_t N); Changes the number of buckets to N, a relatively expensive operation if there are many items in the collection.
22 RWTValHashDictionaryIterator Synopsis #include unsigned hashFun(const K&); RWTValHashDictionary dictionary(hashFun); RWTValHashDictonaryIterator iterator(dictionary); Description Iterator for class RWTValHashDictionary , allowing sequential access to all keys and values of a parameterized hash dictionary. Elements are not accessed in any particular order. Like all Tools.
22 void reset(); Resets the iterator to the state it had immediately after construction. void reset(RWTValHashDictionary& c); Resets the iterator to iterate over the collection c. V value() const; Returns the value at the iterator's current position. The results are undefined if the iterator is no longer valid.
22 RWTValHashSet RWTValHashSet | RWTValHashTable Synopsis #include unsigned hashFun(const T&); RWTValHashSet(hashFun) set; Description RWTValHashSet is a derived class of RWTValHashTable where the insert() function has been overridden to accept only one item of a given value. Hence, each item in the collection will be unique. As with class RWTValHashTable , you must supply a hashing function to the constructor.
22 Example This examples exercises a set of RWCStrings . #include #include #include unsigned hashIt(const RWCString& str){ return str.hash(); } main() { RWTValHashSet set(hashIt); set.insert("one"); set.insert("two"); set.insert("three"); set.insert("one"); // Rejected: already in collection cout << set.
22 void insert(const T& val); Redefined from class RWTValHashTable to allow an object of a given value to be inserted only once. RWBoolean isEmpty() const; Inherited from class RWTValHashTable . size_t occurrencesOf(const T& val) const; Inherited from class RWTValHashTable . RWBoolean remove(const T& val); Inherited from class RWTValHashTable . size_t removeAll(const T& val); Inherited from class RWTValHashTable . void resize(size_t N); Inherited from class RWTValHashTable .
22 RWTValHashTable Synopsis #include unsigned hashFun(const T&); RWTValHashTable table(hashFun); Description This class implements a parameterized hash table of types T. It uses chaining to resolve hash collisions. Duplicates are allowed. It is a value based collection: objects are copied in and out of the hash buckets. Parameter T represents the type of object to be inserted into the table, either a class or built in type.
22 If you wish this to be automatically done, then you can subclass from this class and implement your own special insert() and remove() functions which perform a resize() as necessary. Example #include #include #include unsigned hashIt(const RWCString& str) {return str.hash();} main() { RWTValHashTable table(hashIt); table.insert("Alabama"); // NB: Type conversion occurs table.insert("Pennsylvania"); table.insert("Oregon"); table.
22 Public constructors RWTValHashTable(unsigned (*hashFun)(const T&), size_t buckets = RWDEFAULT_CAPACITY); Constructs a new hash table. The first argument is a pointer to a user-defined hashing function for items of type T. The table will initally have buckets buckets although this can be changed with member function resize() . RWTValHashTable(const RWTValHashTable& table); Constructs a new hash table as a copy of table . The new table will have the same number of buckets as the old table.
22 void insert(const T& val); Inserts the value val into the collection. RWBoolean Returns TRUE isEmpty() const; if the collection has no items in it, FALSE otherwise. size_t occurrencesOf(const T& val) const; Returns the number of items in the collection which are equal to val . Equality is measured by the class-defined equality operator. RWBoolean remove(const T& val); Removes the first object which is equal to the object a and returns TRUE . Returns FALSE if there is no such object.
22 RWTValHashTableIterator Synopsis #include RWTValHashTable table; RWTValHashTableIterator iterator(table); Description Iterator for class RWTValHashTable , allowing sequential access to all the elements of a hash table. Elements are not accessed in any particular order. Like all Tools.h++ iterators, the "current item" is undefined immediately after construction—you must define it by using operator() or some other (valid) operation.
22 RWTValOrderedVector Synopsis #include RWTValOrderedVector ordvec; Description RWTValOrderedVector is an ordered collection. That is, the items in the collection have a meaningful ordered relationship with respect to one another and can be accessed by an index number. The order is set by the order of insertion. Duplicates are allowed.
22 Example #include #include main() { RWTValOrderedVector vec; vec.insert(22.0); vec.insert(5.3); vec.insert(-102.5); vec.insert(15.0); vec.insert(5.3); cout << vec.entries() << " entries\n" << endl; for (int i=0; i(size_t capac=RWDEFAULT_CAPACITY); Create an empty ordered vector with capacity capac .
22 Public operators RWTValOrderedVector& operator=(const RWTValOrderedVector& c); Sets self to a copy of c. The copy constructor of all elements in the vector will be called. Self will have the same capacity and number of members as the old vector. T& operator()(size_t i); T operator()(size_t i) const; Returns the i'th value in the vector. The first variant can be used as an l-value, the second cannot. The index i must be between zero and the number of items in the collection less one.
22 RWBoolean find(const T& a,T& ret) const; Performs a linear search and returns TRUE if the vector contains an object that is equal to the object a and puts a copy of the matching object into ret . Returns FALSE otherwise and does not touch ret . Equality is measured by the class-defined equality operator. T first() const; Returns the first item in the collection. An exception of type TOOL_INDEX will occur if the vector is empty.
22 void prepend(const T& a); Prepends the value a to the beginning of the vector. The collection will automatically be resized if this causes the number of items in the collection to exceed the capacity. RWBoolean remove(const T& a); Performs a linear search, removing the first object which is equal to the object a and returns TRUE . Returns FALSE if there is no such object. Equality is measured by the class-defined equality operator.
22 RWTValSlist Synopsis #include RWTValSlist list; Description This class maintains a collection of values, implemented as a singly linked list. This is a value based list: objects are copied in and out of the links that make up the list. Unlike intrusive lists (see class RWTIsvSlist ) the objects need not inherit from a link class.
22 Code Example 22-7 (Continued) if (dates.find(RWDate(2, "June", 52), ret)){ cout << "Found date " << ret << endl; } // Remove in reverse order: while (!dates.isEmpty()) cout << dates.removeLast() << endl; return 0; } Program output: Found date June 2, 1952 April 1, 1990 March 30, 1946 June 2, 1952 Public constructors RWTValSlist(); Construct an empty list. RWTValSlist(const RWTValSlist& list); Construct a copy of the list list .
22 T operator[](size_t i) const; Returns a copy of the item at index i. The results cannot be used as an lvalue. An exception of type TOOL_INDEX will be thrown if i is not a valid index. Valid indices are from zero to the number of items in the list less one. Public member functions void Adds the item a append(const T& a); to the end of the list. void apply(void (*applyFun)(T&, void*), void* d); Applies the user-defined function pointed to by applyFun to every item in the list.
22 For each item in the list this function will be called with the item as the first argument. Client data may be passed through as parameter d. size_t entries() const; Returns the number of items that are currently in the collection. RWBoolean find(const T& a, T& k) const; Returns TRUE if the list contains an object that is equal to the object a and puts a copy of the matching object into k. Returns FALSE otherwise and does not touch k. Equality is measured by the class-defined equality operator.
22 Returns the index of the first object for which the user-defined tester function pointed to by testFun returns TRUE , or RW_NPOS if there is no such object. The tester function must have the prototype: RWBoolean yourTester (const T&, void* d); For each item in the list this function will be called with the item as the first argument. Client data may be passed through as parameter d. void Adds the item a insert(const T& a); to the end of the list.
22 RWBoolean remove(const T& a); Removes the first object which is equal to the object a and returns TRUE . Returns FALSE if there is no such object. Equality is measured by the classdefined equality operator. RWBoolean remove(RWBoolean (*testFun) (const T&, void*), void* d); Removes the first object for which the user-defined tester function pointed to by testFun returns TRUE , and returns TRUE . Returns FALSE if there is no such object.
22 T removeLast() Removes and returns the last item in the list. The behavior is undefined if the list is empty. This function is relatively slow because removing the last link in a singly-linked list necessitates access to the next-to-the-last link, requiring the whole list to be searched.
22 RWTValSlistIterator Synopsis #include RWTValSlist iterator(list); Description Iterator for class RWTValSlist , allowing sequential access to all the elements of a singly-linked parameterized list. Elements are accessed in order, from first to last. Like all Tools.h++ iterators, the "current item" is undefined immediately after construction—you must define it by using operator() or some other (valid) operation.
22 Public member functions RWTValSlist* container() const; Returns a pointer to the collection over which this iterator is iterating. RWBoolean findNext(const T& a); Advances the iterator to the first element that is equal to a and returns TRUE , or FALSE if there is no such element. Equality is measured by the class-defined equality operator for type T.
22 void reset(); Resets the iterator to the state it had immediately after construction. void reset(RWTValSlist& c); Resets the iterator to iterate over the collection c.
22 RWTValSortedVector Synopsis #include RWTValSortedVector sortvec; Description RWTValSortedVector is an ordered collection. That is, the items in the collection have a meaningful ordered relationship with respect to each other and can be accessed by an index number. In the case of RWTValSortedVector , objects are inserted such that objects "less than" themselves are before the object, objects "greater than" themselves after the object. An insertion sort is used.
22 Example This example inserts a set of dates into a sorted vector in no particular order, then prints them out in order. #include #include #include main() { RWTValSortedVector vec; vec.insert(RWDate(10, "Aug", 1991)); vec.insert(RWDate(9, "Aug", 1991)); vec.insert(RWDate(1, "Sept", 1991)); vec.insert(RWDate(14, "May", 1990)); vec.insert(RWDate(1, "Sept", 1991)); vec.insert(RWDate(2, "June", 1991)); // Add a duplicate for (int i=0; i
22 Public operators T& operator()(size_t i); T operator()(size_t i) const; Returns the i'th value in the vector. The first variant can be used as an l-value, the second cannot. The index i must be between zero and the number of items in the collection less one. No bounds checking is performed. T& operator[](size_t i); T operator[](size_t i) const; Returns the i'th value in the vector. The first variant can be used as an l-value, the second cannot.
22 size_t index(const T& a) const; Performs a binary search, returning the index of the first item that is equal to a. Returns RW_NPOS if there is no such item. Equality is measured by the classdefined equality operator. void insert(const T& a); Performs a binary search, inserting a after all items that compare less than or equal to it, but before all items that do not. "Less Than" is measured by the class-defined '<' operator for type T.
22 T removeLast(); Removes and returns the last object in the collection. An exception of type TOOL_INDEX will be thrown if the list is empty. void resize(size_t N); Changes the capacity of the collection to N. Note that the number of objects in the collection does not change, just the capacity.
22 RWTValVector Synopsis #include RWTValVector vec; Descripton Class RWTValVector is a simple parameterized vector of objects of type T. It is most useful when you know precisely how many objects have to be held in the collection. If the intention is to "insert" an unknown number of objects into a collection, then class RWTValOrderedVector may be a better choice. The class T must have: • well-defined copy semantics ( T::T(const T&) or equiv.
22 Program output: March March March March March March March Public constructors 16, 17, 18, 19, 20, 21, 22, 1992 1992 1992 1992 1992 1992 1992 RWTValVector(); Constructs an empty vector of length zero. RWTValVector(size_t n); Constructs a vector of length n. The values of the elements will be set by the default constructor of class T. For a built in type this can (and probably will) be garbage.
22 T operator[](size_t i) const; T& operator[](size_t i); Return the i'th value in the vector. The index i must be between 0 and the length of the vector less one. Bounds checking will be performed. Public member functions const T* data() const; Returns a pointer to the raw data of self. Should be used with care. size_t Returns the length of the vector. length() const; void reshape(size_t N); Changes the length of the vector to N.
22 RWTValVirtualArray Synopsis #include RWVirtualPageHeap* heap; RWTValVirtualArray array(1000L, heap); Description This class represents a virtual array of elements of type T of almost any length. Individual elements are brought into physical memory on an "as needed" basis. If an element is used as an lvalue it is automatically marked as "dirty" and will be rewritten to the swapping medium. The swap space is provided by an abstract page heap which is specified by the constructor.
22 second line, the expression vec[i] is being used as an lvalue. In this case, the compiler uses the assignment operator for RWTVirtualElement . This assignment operator recognizes that the expression is being used as an lvalue and automatically marks the appropriate page as "dirty", thus guaranteeing that it will be written back out to the swapping medium. Slices, as well as individual elements, can also be addressed.
22 Code Example 22-8 (Continued) cout << vec1[300] << endl; // Prints "300" RWTValVirtualArray vec2 = vec.slice(5000L, 500L); cout << vec2.length() << endl; // Prints "500" cout << vec2[0] << endl; // Prints "5000"; return 0; } Program output: 100 300 500 5000 Public constructors RWTValVirtualArray(long size, RWVirtualPageHeap* heap); Construct a vector of length size. The pages for the vector will be allocated from the page heap given by heap which can be of any type.
22 void operator=(const RWTVirtualSlice& sl); Sets self equal to a slice of another vector. The resultant vector will use the same heap as the vector whose slice is being taken. Its length will be given by the length of the slice. The copy will be made immediately. T operator=(const T& val); Sets all elements in self equal to val . This operator is actually quite efficient because it can work with many elements on a single page at once. T operator[](long i) const; Returns a copy of the value at index i.
22 104011 Tandem Computers Incorporated 22-127
22 22-128 104011 Tandem Computers Incorporated
Part 4—
Classes 23 RWGBitVec(size) Synopsis #include 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 . Bits are numbered from 0 through size– 1, inclusive.
23 Example In this example, a bit vector 24 bits long is declared and exercised: #include declare(RWGBitVec,24) implement(RWGBitVec, 24) main() { RWGBitVec(24) a, b; a(2) = TRUE; // declare a 24 bit long vector // implement the vector // Allocate two vectors. // Set bit 2 (the third bit) of a on. b(3) = TRUE; // Set bit 3 (the fourth bit of b on. RWGBitVec(24) c = a ^ b; // Set c to the XOR of a and b.
23 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 i'th 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 i'th bit of self. This reference can be used as an lvalue.
23 Related global functions RWGBitVec(sz) operator&(const RWGBitVec(sz)& v2); RWGBitVec(sz) operator^(const RWGBitVec(sz)& v2); RWGBitVec(sz) operator|(const RWGBitVec(sz)& v2); Return the logical AND, XOR, and OR, RWGBitVec(sz)& v1, const RWGBitVec(sz)& v1, const RWGBitVec(sz)& v1, const 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 .
23 RWGDlist(type) RWGDlist(type) | RWDlist | RWSlist Synopsis #include 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 .
23 Example #include #include declare(RWGDlist,int) /* Declare a list of ints */ main() { RWGDlist(int) list; // Define a list of ints 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( int* ip = next() ) cout << *ip << endl; // Print out the members } Program output: 11 5 7 1 Public constructors RWGDlist( type )(); Construct an empty collection.
23 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 userprovided 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.
23 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.
23 RWGDlistIterator(type) RWGDlistIterator(type) | RWDlistIterator | RWSlistIterator Synopsis #include 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. Like all Tools.
23 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 Advances the iterator one item. operator++(); void operator--(); Moves the iterator back one item. void Advances the iterator n void Moves the iterator back n Public member functions operator+=(size_t n); items. operator-=(size_t n); items.
23 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.
23 RWGOrderedVector(val) Synopsis #include declare(RWGVector, val ) declare(RWGOrderedVector, val ) implement(RWGVector, val ) implement(RWGOrderedVector, val ) RWGOrderedVector (val ) v; type val . Description // Ordered vector of objects of Class RWGOrderedVector (val ) represents an ordered collection of objects of type val. Objects are ordered by the order of insertion and are accessible by index. Duplicates are allowed.
23 For each type 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 . Example Here's an example that uses an ordered vector of RWCStrings . #include #include #include
23 Public member functions val val& operator()(size_t i) const; operator()(size_t i); Return the i'th value in the vector. The index i must be between 0 and the length of the vector less one. 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 i'th value in the vector. The index i must be between 0 and the length of the vector less one. Bounds checking will be performed.
23 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 – The actual number of items in the collection does not change, just the capacity.
23 RWGQueue(type) RWGQueue( type) | RWSlist Synopsis #include 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.
23 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. 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.
23 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.
23 RWGSlist(type) RWGSlist(type) | RWSlist Synopsis #include 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 .
23 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. apply(void (*ap)( type *, void*), void* ); Visits all the items in the collection in order, from first to last, calling the userprovided function pointed to by ap for each item. This function should have prototype: void void yourApplyFunction (type * c, void*); and can perform any operation on the object at address c.
23 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 .
23 type * remove( yourTester t, const void* d); Removes and returns the first item from the collection for which the userprovided 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.
23 RWGSlistIterator(type) RWGSlistIterator(type) | RWSlistIterator Synopsis #include 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. Like all Tools.
23 Public member functions RWBoolean Returns TRUE atFirst() const; if the iterator is at the start of the list, FALSE otherwise; RWBoolean Returns TRUE atLast() const; 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.
23 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.
23 RWGSortedVector(val) RWGSortedVector(val) | RWGVector( val) Synopsis #include declare(RWGSortedVector, val ) implement(RWGSortedVector, val ) RWGSortedVector( val ) v; Description // A sorted vector of val's . Class RWGSortedVector (val ) represents a vector of elements of type val , sorted using an insertion sort. The elements can be retrieved using an index or a search. Duplicates are allowed.
23 For each type 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 – The constructor of a RWGSortedVector( val ) requires a pointer to a “comparison function.
23 Example Here's an example of a sorted vector of ints: #include #include 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); avec.insert(17); avec.
23 Public member functions val operator()(size_t i) const; Return the i'th 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 i'th 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.
23 RWGStack(type) RWGStack(type) | RWSlist Synopsis #include 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.
23 Assignment operator void Public member functions void clear(); Removes all items from the stack. operator=(const RWGStack (type )& a); Assignment operator. A shallow copy of a is made. 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.
23 RWGVector(val) Synopsis #include declare(RWGVector, val ) implement(RWGVector, val ) RWGVector ( val ) a; Description // A Vector of val's . 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 . Note – It is a value-based collection: items are copied in and out of the collection.
23 Example #include #include #include declare(RWGVector, RWDate) implement(RWGVector, RWDate) /* Declare a vector of dates */ /* 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.
23 RWGVector( val )(RWGVector( val )& s); Copy constructor. The entire vector is copied, including all imbedded 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); Returns a reference to the the i'th element of self. The index i must be between zero and the length of the vector less one. No bounds checking is performed.
Summary of typedefs and macros A Constants: #define #define #define const int) const RWoffset FALSE rwnil TRUE RWkeyLen= 16 RWNIL = -1L; 0 0 1 unsigned short unsigned long unsigned int unsigned unsigned long unsigned unsigned unsigned unsigned int long void* unsigned long ClassID;// Unique for each class clockTy;// seconds dayTy;// days fileDescTy;// File descriptor hourTy;// hours julTy;// Julian days minuteTy;// minutes monthTy;// months secondTy;// seconds yearTy;// years RWBoolean;// TRUE or FALSE
A Pointers to Functions: typedef typedef typedef void void void typedef int typedef typedef RWBoolean RWBoolean typedef RWCollectable* (*RWapplyCollectable)(RWCollectable*, void*); (*RWapplyGeneric)(void*, void*); (*RWapplyKeyAndValue) (RWCollectable*,RWCollectable*,void*); (*RWdiskTreeCompare)(const char*,const char*,size_t); (*RWtestGeneric)(const void*,const void*); (*RWtestCollectable)(const RWCollectable*,const void*); (*RWuserCreator)(); RWSeverity {RWWARNING, RWDEFAULT, RWFATAL} Enumeratio
A typedef typedef typedef typedef typedef typedef RWSet RWSetIterator RWSlistCollectables RWSlistCollectablesIterator RWSlistCollectablesQueue RWSlistCollectablesStack 104011 Set; SetIterator; LinkedList; LinkedListIterator; Queue; Stack; Tandem Computers Incorporated A-3
A A-4 104011 Tandem Computers Incorporated
Header file compiler.h B This header file is the repository for all information about compiler related capabilities and limitations. It is included by Tools.h++ libraries. The general philosophy of the various macros defined in is that an ARM compliant compiler does not have any of these macros defined. That is, macros characterize a compiler ’s limitations, rather than its abilities. Table B-1 Summary of preprocessor macros found in . Macro Defined if ...
B Table B-1 Summary of preprocessor macros found in . (Continued) B-2 Macro Defined if ...
C Messages Table C-1 Core messages. These are messages used by all Tools.h++ libraries. The symbols are defined in . These messages belong to category " rwcore6.0 ".
C Table C-2 C-2 Tools.h++ messages. These are messages used by the Tools.h++ library. The symbols are defined in . These messages belong to category " rwtool6.0 ".
C Table C-2 Tools.h++ messages. These are messages used by the Tools.h++ library. The symbols are defined in . These messages belong to category " rwtool6.0 ".
C C-4 104011 Tandem Computers Incorporated
Bibliography D Ammeraal, L. Programs and Data Structures in C, John Wiley and Sons, 1989, ISBN 0-471-91751-6. Booch, Grady, Object-Oriented Design with Applications, The Benjamin Cummings Publishing Company, Inc., 1991, ISBN 0-8053-0091-0 _ . Budd, Timothy, An Introduction to Object-Oriented Programming , AddisonWesley, 1991, ISBN 0-201-54709-0. Coplien, James O., Advanced C++, Programming Styles and Idioms , AddisonWesley, 1992, ISBN 0-201-54855-0 _.
D Lippman, Stanley B. C++ Primer, Addison-Wesley, 1989, ISBN 0-201-16487-6 _ . Meyer, Bertrand, Object-oriented Software Construction , Prentice-Hall, 1988, ISBN 0-13-629049-3. Meyers, Scott, Effective C++ , Addison-Wesley, 1992, ISBN 0-201-56364-9. Petzold, Charles, Programming Windows, Microsoft Press, 1990, ISBN 1-55615264-7. Sedgewick, Robert. Algorithms, Addison-Wesley, 1988, ISBN 0-201-06673-4. Stroustrup, Bjarne. The C++ Programming Language, Addison-Wesley, 1986, ISBN 0-201-12078-X.
Index A abstract 21-64 Apply functions 14-8, 15-12 apply() 14-8, 15-12 B Bag 21-3 Overview 15-6 Benchmarking 21-9 Bibliography D-1 Bit vector 21-24, 22-1, 23-1 Borland C++ binary mode 8-5 BOUNDS_CHECK 13-6 C Caches RWCacheManager 21-50 ClassID 21-53, 21-108, A-1 clear() 15-13 clearAndDestroy() 15-13 clockTy A-1 Collection 21-64 Collection Classes abstract base class 21-64 104011 Tandem Computers Incorporated compareTo() 21-52 dictionary 15-7 generic RWGBitVec(size) 23-1 RWGDlist(type) 23-5 RWGOrderedVe
virtual functions 15-8 Compares equal 12-7 contains() 15-9 Conventions 1-4 Copies shallow vs.
L Q Linked List generic doubly-linked 23-5 singly-linked 23-19 of Collectables doubly-linked 21-101 singly-linked 21-168 Templates doubly-linked 22-21, 22-75 singly-linked 22-52, 22-105 LinkedList 21-168 LinkedListIterator 21-172 Queue 21-175 generic 23-16 of Collectables 21-175 Templates 22-69 M minuteTy A-1 Model-View-Controller 21-142 monthTy A-1 Multiple inheritance 12-7 O Object 21-52 type, state, and identity 12-6 occurrencesOf() 15-9 Ordered collection generic 23-12 Smalltalk-like 21-145 Templat
RWCollection 21-64 RWCRegexp 21-68 RWCString 5-1, 21-60, 21-72 pattern matching 5-5 substrings 21-85 RWCSubString 5-4, 21-85 RWCTokenizer 21-88 RWDate 6-1, 21-56, 21-90 RWDiskPageHeap 21-98 RWdiskTreeCompare A-2 RWDlistCollectables 21-101 RWDlistCollectablesIterator 21-105 RWFactory 21-108 RWFile 8-7, 9-1, 21-110, 21-114 RWFileManager 10-1, 21-114 use with RWBTreeOnDisk 11-1 RWGBitVec(size) 21-24, 23-1 synopsis 23-1 RWGDlist(type) 23-5 RWGDlistIterator(type) 23-9 RWGOrderedVector(val) 23-12 RWGQueue(type) 2
RWTValDlistIterator 22-82 RWTValHashDictionary 22-85 RWTValHashDictionaryIterator 22-90 RWTValHashSet 22-92 RWTValHashTable 22-95 RWTValHashTableIterator 22-99 RWTValOrderedVector 22-100 RWTValSlist 22-105 RWTValSlistIterator 22-112 RWTValSortedVector 22-115 RWTValVector 22-120 RWTValVirtualArray 22-123 RWuserCreator 21-108, A-2 RWVirtualPageHeap 21-48, 21-98, 21-193 RWvistream 21-196 RWvoid A-1 RWvostream 21-201 RWWString 21-205 RWWSubString 21-218 RWWTokenizer 21-221 RWZone 21-233 RWZoneDefault 21-236 S
Y yearTy A-1 Index-6 104011 Tandem Computers Incorporated