libDwm-0.9.45
Dwm Class Library

Introduction

This class library is just a (somewhat random) collection of classes I've developed over the years for various applications. Since these are used in a variety of places, they're collected here to make reuse easy.

There are a few classes herein that I've used on nearly every software project in the last 20 years. One of those would be the Dwm::SysLogger class with the Syslog() macro, since syslogging is a common need. Another would be the Dwm::Assertions class with the UnitAssert() macro since I almost always write unit tests as part of my development process. And when I need to store data, I use the IO classes along with the various Readable and Writable interfaces.

Since much of the software I've written in the last 20 years has been multithreaded, I have also made heavy use of the Dwm::Thread::Queue class for inter-thread communication (usually as 'work queues').

History

I started this library in 1998. I continue to maintain it for my personal use. While it has grown over the years, the most common use features have been stable for a long time. To some extent they have to be stable; I have over 500,000 lines of code in my personal software repository, and a decent amount of it is dependent on this library. The good news is that those dependencies don't prevent me from refactoring, improving and growing libDwm as needed.

Platforms

I really only maintain support for 4 platforms: FreeBSD, macOS, desktop linux and Raspberry Pi OS. FreeBSD is my operating system of choice for servers and macOS is my operating system of choice for desktops and laptops. I have several Raspberry Pis I utilize for simple small tasks, and Ubuntu VMs and Ubuntu workstations.

A small sample of what's in libDwm

I/O - Serialization

Dwm::DescriptorIO, Dwm::FileIO, Dwm::StreamIO, Dwm::ASIO, Dwm::GZIO and Dwm::BZ2IO provide serialization for intrinsic types, containers of intrinsic types, user types which implement the required interfaces, and containers of these user types.

Intrinsic integer types are written in network byte order. The library takes care of byte ordering so you need not be concerned with it. Float and double types are written in IEEE 754-1985 form (see RFC 1832). Some types are stored as (length,value) pairs, including the standard containers and C++ string objects.

For user types, the required interfaces are *Readable and *Writable, such as Dwm::StreamReadable and Dwm::StreamWritable. The required interfaces for Dwm::GZIO are Dwm::GZReadable and Dwm::GZWritable. The required interfaces for Dwm::BZ2IO are Dwm::BZ2Readable and Dwm::BZ2Writable.

Note that inheritance from the aforementioned interface classes is no longer required, and is in fact discouraged. Today, the Dwm::*IO classes use concepts instead. You'll see these concepts at the top of the various *IOCapable.hh header files, which just express the same interface requirements as the pure virtual classes. This allows the library user to avoid inheriting from the pure virtual classes.

I wrote most of this functionality in 2004 when we didn't have a lot of options to support serialization. I finalized most of it in 2007 with the addition of cleaner code for std::tuple. I couldn't do this effectively until the compilers and standard libraries were up to speed. With C++11 and beyond, I was able to simplify some of the code thanks to things like variadic templates. Given that we now have C++23 and still no reflection, this work has paid big dividends for me.

Why did I spend time on this functionality? I frequently need to do things like this (error checking absent for the sake of brevity):

1#include <fstream>
2#include <map>
3#include <string>
4
5#include "DwmIpv4Address.hh"
6#include "DwmStreamIO.hh"
7
8int main(int argc, char *argv[])
9{
10 std::map<Dwm::Ipv4Address, std::string> hosts;
11
12 // Read hosts from an ifstream
13 std::ifstream is("/tmp/hosts");
14
15 if (is) {
16 Dwm::StreamIO::Read(is, hosts);
17 is.close();
18 }
19
20 // Do something with hosts, then...
21
22 // Save hosts to an ofstream
23 std::ofstream os("/tmp/hosts");
24 if (os) {
25 Dwm::StreamIO::Write(os, hosts);
26 os.close();
27 }
28
29 return 0;
30}
31
32
Dwm::Ipv4Address class definition.
Dwm::StreamIO class declaration.
static std::istream & Read(std::istream &is, char &c)
Reads c from is. Returns is.
static std::ostream & Write(std::ostream &os, char c)
Writes c to os. Returns os.

While this is a trivial example, I've used this functionality in much more complex scenarios. Having this type of functionality in my toolbox has saved me large amounts of development time. It's reasonably flexible without a lot of extra work. No work at all if you're using types already supported. Containers of containers of supported types, for example:

1#include <fstream>
2#include <map>
3#include <set>
4#include <string>
5#include <vector>
6
7#include "DwmStreamIO.hh"
8
9using namespace std;
10
11int main(int argc, char *argv[])
12{
13 if (argc > 2) {
14 vector<map<string,set<string>>> data;
15
16 // Read data from an ifstream
17 ifstream is(argv[1]);
18 if (is) {
19 Dwm::StreamIO::Read(is, data);
20 is.close();
21 }
22
23 // Do something with the data...
24
25 // Then save to an ofstream
26 ofstream os(argv[2]);
27 if (os) {
28 Dwm::StreamIO::Write(os, data);
29 os.close();
30 }
31 }
32
33 return 0;
34}

Since the library handles C++ <tuple>, you can create new data classes and easily add serialization by keeping all of your class's data in a tuple. Below is a trivial contrived example of a phone contact data store. The serialization members required are lines 44 to 49 and 110 to 115. These are easy to implement, since they each require only a single call to a member of an I/O class. Note that I never put  using namespace std in header files. It's here just to reduce clutter on your screen.

1#include "DwmDescriptorIO.hh"
2#include "DwmFileIO.hh"
3#include "DwmStreamIO.hh"
4
5using namespace std;
6
7//----------------------------------------------------------------------------
8//----------------------------------------------------------------------------
9class PhoneContact
10{
11public:
12 PhoneContact() : _data() { }
13
14 const string & FirstName() const { return get<0>(_data); }
15 const string & FirstName(const string & firstName)
16 {
17 get<0>(_data) = firstName;
18 return get<0>(_data);
19 }
20
21 const string & LastName() const { return get<1>(_data); }
22 const string & LastName(const string & lastName)
23 {
24 get<1>(_data) = lastName;
25 return get<1>(_data);
26 }
27
28 const set<pair<string,string> > & PhoneNumbers() const
29 { return get<2>(_data); }
30 bool AddPhoneNumber(const string & phoneName,
31 const string & phoneNumber)
32 {
33 pair<string,string> phone(phoneName, phoneNumber);
34 return get<2>(_data).insert(phone).second;
35 }
36
37 bool RemovePhoneNumber(const string & phoneName,
38 const string & phoneNumber)
39 {
40 pair<string,string> phone(phoneName, phoneNumber);
41 return (get<2>(_data).erase(phone) == 1);
42 }
43
44 istream & Read(istream & is) { return Dwm::StreamIO::Read(is, _data); }
45 ostream & Write(ostream & os) const { return Dwm::StreamIO::Write(os, _data); }
46 ssize_t Read(int fd) { return Dwm::DescriptorIO::Read(fd, _data); }
47 ssize_t Write(int fd) const { return Dwm::DescriptorIO::Write(fd, _data); }
48 size_t Read(FILE *f) { return Dwm::FileIO::Read(f, _data); }
49 size_t Write(FILE *f) const { return Dwm::FileIO::Write(f, _data); }
50
51private:
52 tuple<string, // first name
53 string, // last name
54 set<pair<string,string> > // phone numbers
55 > _data;
56};
57
58//----------------------------------------------------------------------------
59//----------------------------------------------------------------------------
60class PhoneContacts
61{
62public:
63 PhoneContacts() : _contacts() { }
64
65 bool AddContact(const PhoneContact & contact)
66 {
67 bool rc = false;
68 string fullName(contact.FirstName() + " " + contact.LastName());
69 auto it = _contacts.find(fullName);
70 if (it == _contacts.end()) {
71 _contacts[fullName] = contact;
72 rc = true;
73 }
74 return rc;
75 }
76
77 bool MatchesByEitherName(const string & name,
78 vector<PhoneContact> & matches) const
79 {
80 if (! matches.empty()) {
81 matches.clear();
82 }
83 for (auto i : _contacts) {
84 if ((i.second.FirstName() == name)
85 || (i.second.LastName() == name)) {
86 matches.push_back(i.second);
87 }
88 }
89 return (! matches.empty());
90 }
91
92 bool MatchByFullName(const string & firstName, const string & lastName,
93 PhoneContact & match)
94 {
95 bool rc = false;
96 for (auto i : _contacts) {
97 if ((i.second.FirstName() == firstName)
98 && (i.second.LastName() == lastName)) {
99 match = i.second;
100 rc = true;
101 break;
102 }
103 }
104 return rc;
105 }
106
107 const map<string,PhoneContact> & Contacts() const { return _contacts; }
108 map<string,PhoneContact> & Contacts() { return _contacts; }
109
110 istream & Read(istream & is) { return Dwm::StreamIO::Read(is, _contacts); }
111 ostream & Write(ostream & os) const { return Dwm::StreamIO::Write(os, _contacts); }
112 ssize_t Read(int fd) { return Dwm::DescriptorIO::Read(fd, _contacts); }
113 ssize_t Write(int fd) const { return Dwm::DescriptorIO::Write(fd, _contacts); }
114 size_t Read(FILE *f) { return Dwm::FileIO::Read(f, _contacts); }
115 size_t Write(FILE *f) const { return Dwm::FileIO::Write(f, _contacts); }
116
117private:
118 map<string,PhoneContact> _contacts;
119};
120
Dwm::DescriptorIO class declaration.
Dwm::FileIO class declaration.
static ssize_t Write(int fd, char c)
Writes c to fd.
static ssize_t Read(int fd, char &c)
Reads c from fd.
static size_t Write(FILE *f, char c)
Writes c to f.
static size_t Read(FILE *f, char &c)
Reads c from f.

The astute observer will notice that the PhoneContact class is just a wrapper around a std::tuple, to avoid having to use std::get<>() directly from application code outside of this class. If you're willing to deal directly with std::get<>(), you can just do this:

typedef std::tuple<std::string,std::string,std::pair<std::string,std::string> > > PhoneContact;
typedef std::map<std::string,PhoneContact> PhoneContacts;

UnitAssert - A trivial unit testing framework

In DwmUnitAssert.hh you will find the UnitAssert() macro and a handful of support classes for unit testing. This trivial framework makes simple unit testing easy to accomplish for all exposed interfaces. This framework is used for all of the unit tests in the tests subdirectory of the libDwm source distribution, and you can look there for many examples. But its basic usage is trivial and typically boils down to just three calls: the UnitAssert() macro to assert conditions that must be true (just like assert() from the standard C library), and a call to Dwm::Assertions::Print() at the end of your test program that is typically wrapped in test of the return of Dwm::Assertions::Total().Failed().

Below is the entire contents of TestGroup.cc from the tests directory of the libDwm source distribution. You will see calls to UnitAssert() on lines 16, 21, 26, 27 and 28. On line 30, we check if there were any failed tests via Dwm::Assertions::Total().Failed(). If there were, we print them with Dwm::Assertions::Print(). If there were no failed tests, we print the total number of tests (which all passed).

1extern "C" {
2 #include <unistd.h>
3}
4
5#include "DwmGroup.hh"
6#include "DwmPassword.hh"
7#include "DwmUnitAssert.hh"
8
9//----------------------------------------------------------------------------
11//----------------------------------------------------------------------------
12int main(int argc, char *argv[])
13{
14 gid_t mygid = getegid();
15 Dwm::Group mygroup(mygid);
16 UnitAssert(mygid == mygroup.Id());
17
18 Dwm::Password mypasswd(geteuid());
19 auto gmit = std::find(mygroup.Members().begin(), mygroup.Members().end(),
20 mypasswd.UserName());
21 UnitAssert(gmit != mygroup.Members().end());
22
23 struct group *grp = getgrgid(mygid);
24 Dwm::Group setGroup(getgid());
25 setGroup.Set(*grp);
26 UnitAssert(setGroup.Id() == grp->gr_gid);
27 UnitAssert(setGroup.Name() == grp->gr_name);
28 UnitAssert(setGroup.Password() == grp->gr_passwd);
29
30 if (Dwm::Assertions::Total().Failed() > 0) {
31 Dwm::Assertions::Print(std::cerr, true);
32 exit(1);
33 }
34 else {
35 std::cout << Dwm::Assertions::Total() << " passed" << std::endl;
36 }
37 exit(0);
38}
Dwm::Group class definition.
Dwm::Password class definition.
Dwm::Assertions class definition and UnitAssert() macro for unit tests.
#define UnitAssert(e)
This macro is used just like assert(), but populates Assertions so we can report results at the end o...
Definition DwmUnitAssert.hh:303
static std::ostream & Print(std::ostream &os, bool onlyFailed=false)
Prints to an ostream.
static AssertionCounter Total()
Returns the total passed and failed counter.
Encapsulates an /etc/group entry.
Definition DwmGroup.hh:61
Encapsulates an /etc/passwd entry.
Definition DwmPassword.hh:61

Dwm::SysLogger - decorated syslogging

The intent of Dwm::SysLogger and the Syslog() macro is to allow the automatic addition of filename, line number and syslog priority to syslog messages. No one in their right mind wants to have to add "(%s:%d)", __FILE__, __LINE__ to every syslog call in their source code. It's inane work and prone to mistakes. Syslog() can do this for you if you enable it with Dwm::SysLogger::ShowFileLocation(bool). It can also put three-character tags on each log message if you enable it with Dwm::SysLogger::ShowPriorities(bool). You can also change the minimum priority of messages to be logged via Dwm::SysLogger::MinimumPriority(int) or Dwm::SysLogger::MinimumPriority(const std::string &). This is handy when you want to toggle debug logging while a program is running, perhaps via a signal.