Implementing IXmlWriter Part 13: Putting IXmlWriter Behind A Pimpl Firewall
Implementing IXmlWriter c++ ixmlwriter pimpl xml
Published: 2005-12-15
Implementing IXmlWriter Part 13: Putting IXmlWriter Behind A Pimpl Firewall

This is part 13/14 of my Implementing IXmlWriter post series.

As the private members of IXmlWriter are getting too numerous and too likely to change by my judgment, today I will put last time’s IXmlWriter behind a compilation firewall (pimpl).

The idea behind the pimpl idiom is to hide as much of the class definition as possible in order to avoid requiring users of the class to recompile if the class’s private members are changed. It is accomplished by moving all private members (functions, data, etc.) into a separate class (called the implementation or pimpl class) hidden from the class definition, and replacing these members with an opaque pointer to a forward declaration of this class. It works because a C++ compiler does not need to have the full definition of a class visible in order to allocate space for a pointer to the class; every pointer is a constant, fixed size (often 4 bytes).

Guru of the Week (GotW) #24: Compilation Firewalls contains some discussion about what should belong within the pimpl class, which led me to choose to move all private type definitions, functions, and data into the pimpl class. GotW #24 also mentions some negative performance impact with respect to instantiation and the extra indirections required for accessing private members. The performance impact associated with instantiation can be mitigated by following the lessons of GotW #28: The Fast Pimpl Idiom, but I believe that instances of IXmlWriter will be created relatively infrequently and thus the extra effort required is not worth it. The impact based on the extra indirections we will just have to live with; I highly doubt a profile would identify the extra indirections as a performance bottleneck for IXmlWriter.

The steps required to modify IXmlWriter to use the pimpl idiom are:

  1. In the implementation file, create an internal class (a struct StringXmlWriter::StringXmlWriterImpl, in my case) and move all private members, including the implementations of the private functions, into this class. If applicable, write constructors for the pimpl class which perform the same initializations of private members that the constructors on your original class did.
  2. Within the class definition in the header file, add a forward declaration to this implementation class (e.g. struct StringXmlWriterImpl;) and a member which contains a pointer to this class (e.g. StringXmlWriterImpl* m_pimpl;). This should be the only private member left in the class. (Why not use std::auto_ptr<StringXmlWriterImpl>? See this code comments forum thread.)
  3. Now that you have a pointer variable as a member of the class, the default copy constructor and assignment operators are wrong. Either disable them (as I have done) or write correct implementations.
  4. Modify every constructor of your original class to create an instance of the pimpl class using new and the appropriate pimpl constructor.
  5. Add a destructor to your original class which deletes the instance of the pimpl class.
  6. In the implementation file, modify all references to private types and data to indirect through the pimpl instance. For example, m_xmlStr = ...; becomes m_pimpl->m_xmlStr = ...;.

Here’s the resulting header file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// StringXmlWriter.h

class StringXmlWriter
{
public:
    enum Formatting
    {
        Formatting_Indented,
        Formatting_None
    };

    StringXmlWriter(Formatting formatting = Formatting_None,
                    int indentation = 2,
                    char indentChar = " ");
    ~StringXmlWriter();

    std::string GetXmlString() const;
    void WriteAttributeString(const std::string& localName,
                              const std::string& text);
    void WriteAttributeString(const std::string& localName,
                              const std::string& ns,
                              const std::string& text);
    void WriteComment(const std::string& text);
    void WriteElementString(const std::string& localName,
                            const std::string& text);
    void WriteElementString(const std::string& localName,
                            const std::string& ns,
                            const std::string& text);
    void WriteEndAttribute();
    void WriteEndDocument();
    void WriteEndElement();
    void WriteStartAttribute(const std::string& localName);
    void WriteStartAttribute(const std::string& localName,
                             const std::string& ns);
    void WriteStartDocument();
    void WriteStartElement(const std::string& localName);
    void WriteStartElement(const std::string& localName,
                           const std::string& ns);
    void WriteString(const std::string& text);

private:
    struct StringXmlWriterImpl;
    StringXmlWriterImpl* m_pimpl;

private:
    // Disable copy construction and assignment
    StringXmlWriter(const StringXmlWriter&);
    StringXmlWriter& operator=(const StringXmlWriter&);
};

Here’s the resulting implementation file:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
// StringXmlWriter.cpp

#include "StringXmlWriter.h"

#define ARRAYSIZE(x) ( sizeof(x) / sizeof(x[0]) )

struct CharTranslation
{
    char OriginalChar;
    const char* ReplacementString;
};

static const CharTranslation AttributeValueTranslations[] =
{
    { '"', "&quot;" },
    { '&', "&amp;" },
};

static const CharTranslation CharDataTranslations[] =
{
    { '&', "&amp;" },
    { '<', "&lt;" },
    { '>', "&gt;" },
};

struct OriginalCharEquals :
    public std::binary_function<CharTranslation, char, bool>
{
    bool operator() (const CharTranslation& translation, char ch) const
    {
        return (translation.OriginalChar == ch);
    }
};

static std::string TranslateString(const std::string& originalStr,
                                   const CharTranslation* translations,
                                   int numTranslations)
{
    // Actually one past end, needed for proper std::find_if semantics
    const CharTranslation* endTranslations = translations + numTranslations;

    std::string translatedStr;
    for (std::string::const_iterator stringIter = originalStr.begin();
         stringIter != originalStr.end();
         ++stringIter)
    {
        char ch = *stringIter;

        const CharTranslation* translation = std::find_if
            (
            translations,
            endTranslations,
            std::bind2nd(OriginalCharEquals(), ch)
            );
        if (translation != endTranslations)
        {
            translatedStr += translation->ReplacementString;
        }
        else
        {
            translatedStr += ch;
        }
    }

    return translatedStr;
}

struct StringXmlWriter::StringXmlWriterImpl
{
    StringXmlWriterImpl(Formatting formatting,
                        int indentation,
                        char indentChar) :
        m_writeState(WriteState_Start),
        m_formatting(formatting),
        m_contentWritten(false)
    {
        for (int i = 0; i < indentation; ++i)
        {
            m_indentStr += indentChar;
        }
    }

    // PRIVATE TYPES
    // =============
    enum WriteState
    {
        WriteState_Attribute, // An attribute value is being written
        WriteState_Content, // Element content is being written
        WriteState_Element, // An element start tag has been written (and is unclosed)
        WriteState_Prolog, // The prolog is being written
        WriteState_Start, // No Write() methods have been called
    };

    struct OpenElement
    {
        explicit OpenElement(const std::string& localName) :
            QName(localName)
        {
        }

        explicit OpenElement(const std::string& localName,
                             const std::string& prefix) :
            QName(prefix.empty() ? localName : prefix + ":" + localName)
        {
        }

        // The qualified name (namespace prefix-included) of the
        // opened element
        std::string QName;
        // All namespaces declared in this element (maps namespace
        // to namespace prefix)
        typedef std::map<std::string, std::string> Namespaces_t;
        Namespaces_t Namespaces;
    };

    // PRIVATE MEMBERS
    // ===============
    WriteState m_writeState;

    // Need to use a vector instead of a stack because we must be able
    // to iterate over each opened element in the stack to see if a
    // namespace has already been declared.
    typedef std::vector<OpenElement> OpenedElements_t;
    OpenedElements_t m_openedElements;

    // Needed to track whether content was written inside the XML element
    // so we know how to handle indentation.
    bool m_contentWritten;

    // The style of formatting we are using.
    StringXmlWriter::Formatting m_formatting;

    // The string to use for a single level of indentation.
    std::string m_indentStr;

    // The XML fragment that this class has generated so far. There's no
    // guarantee it will be valid unless WriteEndDocument() is called.
    std::string m_xmlStr;

    // PRIVATE FUNCTIONS
    // =================
    std::string GetExistingNamespacePrefix(const std::string& ns)
    {
        for (OpenedElements_t::const_iterator openElemIter = m_openedElements.begin();
             openElemIter != m_openedElements.end();
             ++openElemIter)
        {
            OpenElement::Namespaces_t::const_iterator nsIter =
                openElemIter->Namespaces.find(ns);
            if (nsIter != openElemIter->Namespaces.end())
            {
                return nsIter->second;
            }
        }

        return "";
    }

    std::string GetNextNamespacePrefix(const std::string& ns)
    {
        std::string nsPrefix;

        for (int i = 1; ; ++i)
        {
            std::stringstream ss;
            ss << "ns" << i;
            std::string nsPrefix = ss.str();
            if (!NamespacePrefixExists(nsPrefix))
                return nsPrefix;
        }
    }

    bool NamespacePrefixExists(const std::string& nsPrefix)
    {
        for (OpenedElements_t::const_iterator iter = m_openedElements.begin();
             iter != m_openedElements.end();
             ++iter)
        {
            for (OpenElement::Namespaces_t::const_iterator nsIter = iter->Namespaces.begin();
                 nsIter != iter->Namespaces.end();
                 ++nsIter)
            {
                if (nsIter->second == nsPrefix)
                    return true;
            }
        }

        return false;
    }

    void CloseOpenElement()
    {
        m_xmlStr += '>';
        m_writeState = WriteState_Content;
    }

    void NewlineAndIndent()
    {
        assert(m_formatting == Formatting_Indented);

        if (!m_xmlStr.empty())
            m_xmlStr += '\n';

        for (int i = 0; i != m_openedElements.size(); ++i)
        {
            m_xmlStr += m_indentStr;
        }
    }
};

StringXmlWriter::StringXmlWriter(Formatting formatting,
                                 int indentation,
                                 char indentChar) :
    m_pimpl(new StringXmlWriterImpl(formatting, indentation, indentChar))
{
}

StringXmlWriter::~StringXmlWriter()
{
    delete m_pimpl;
}

std::string StringXmlWriter::GetXmlString() const
{
    return m_pimpl->m_xmlStr;
}

void StringXmlWriter::WriteAttributeString(const std::string& localName,
                                           const std::string& text)
{
    WriteStartAttribute(localName);
    WriteString(text);
    WriteEndAttribute();
}

void StringXmlWriter::WriteAttributeString(const std::string& localName,
                                           const std::string& ns,
                                           const std::string& text)
{
    WriteStartAttribute(localName, ns);
    WriteString(text);
    WriteEndAttribute();
}

void StringXmlWriter::WriteComment(const std::string& text)
{
    switch (m_pimpl->m_writeState)
    {
    case StringXmlWriterImpl::WriteState_Element:
        // An element is currently open. Close the element so we can open
        // a new one.
        m_pimpl->CloseOpenElement();
        // FALL THROUGH
    case StringXmlWriterImpl::WriteState_Content:
    case StringXmlWriterImpl::WriteState_Prolog:
    case StringXmlWriterImpl::WriteState_Start:
        if (m_pimpl->m_formatting == Formatting_Indented)
        {
            m_pimpl->NewlineAndIndent();
        }

        m_pimpl->m_xmlStr += "<!--";
        m_pimpl->m_xmlStr += text;
        m_pimpl->m_xmlStr += "-->";
        break;
    default:
        // It doesn't make sense to allow writing comments when writing an
        // attribute value.
        // TODO: Generate error
        break;
    }
}

void StringXmlWriter::WriteElementString(const std::string& localName,
                                         const std::string& text)
{
    WriteStartElement(localName);
    WriteString(text);
    WriteEndElement();
}

void StringXmlWriter::WriteElementString(const std::string& localName,
                                         const std::string& ns,
                                         const std::string& text)
{
    WriteStartElement(localName, ns);
    WriteString(text);
    WriteEndElement();
}

void StringXmlWriter::WriteEndAttribute()
{
    switch (m_pimpl->m_writeState)
    {
    case StringXmlWriterImpl::WriteState_Attribute:
        m_pimpl->m_xmlStr += '"';
        m_pimpl->m_writeState = StringXmlWriterImpl::WriteState_Element;
        break;
    default:
        // TODO: Generate error
        break;
    }
}

void StringXmlWriter::WriteEndDocument()
{
    switch (m_pimpl->m_writeState)
    {
    case StringXmlWriterImpl::WriteState_Attribute:
        WriteEndAttribute();
        // FALL THROUGH
    case StringXmlWriterImpl::WriteState_Content:
    case StringXmlWriterImpl::WriteState_Element:
        while (!m_pimpl->m_openedElements.empty())
        {
            WriteEndElement();
        }
        break;
    case StringXmlWriterImpl::WriteState_Start:
    case StringXmlWriterImpl::WriteState_Prolog:
        // DO NOTHING
        break;
    default:
        // TODO: Generate error
        break;
    }

    m_pimpl->m_writeState = StringXmlWriterImpl::WriteState_Start;
}

void StringXmlWriter::WriteEndElement()
{
    switch (m_pimpl->m_writeState)
    {
    case StringXmlWriterImpl::WriteState_Content:
        {
            std::string qname = m_pimpl->m_openedElements.back().QName;
            m_pimpl->m_openedElements.pop_back();

            if (!m_pimpl->m_contentWritten &&
                m_pimpl->m_formatting == Formatting_Indented)
            {
                m_pimpl->NewlineAndIndent();
            }

            m_pimpl->m_xmlStr += "</";
            m_pimpl->m_xmlStr += qname;
            m_pimpl->m_xmlStr += '>';
            m_pimpl->m_writeState = StringXmlWriterImpl::WriteState_Content;
            break;
        }
    case StringXmlWriterImpl::WriteState_Element:
        {
            m_pimpl->m_xmlStr += "/>";
            m_pimpl->m_openedElements.pop_back();
            m_pimpl->m_writeState = StringXmlWriterImpl::WriteState_Content;
            break;
        }
    default:
        // TODO: Generate error
        break;
    }
}

void StringXmlWriter::WriteStartAttribute(const std::string& localName)
{
    WriteStartAttribute(localName, "");
}

void StringXmlWriter::WriteStartAttribute(const std::string& localName,
                                          const std::string& ns)
{
    switch (m_pimpl->m_writeState)
    {
    case StringXmlWriterImpl::WriteState_Element:
        {
        std::string nsPrefix;
        bool mustDeclareNamespace = false;

        if (!ns.empty()) {
            nsPrefix = m_pimpl->GetExistingNamespacePrefix(ns);
            if (nsPrefix.empty()) {
                nsPrefix = m_pimpl->GetNextNamespacePrefix(ns);
                m_pimpl->m_openedElements.back().Namespaces[ns] = nsPrefix;
                mustDeclareNamespace = true;
            }
        }

        if (mustDeclareNamespace) {
            m_pimpl->m_xmlStr += " xmlns:";
            m_pimpl->m_xmlStr += nsPrefix;
            m_pimpl->m_xmlStr += "=\"";
            m_pimpl->m_xmlStr += ns;
            m_pimpl->m_xmlStr += '"';
        }

        m_pimpl->m_xmlStr += ' ';
        if (!nsPrefix.empty()) {
            m_pimpl->m_xmlStr += nsPrefix;
            m_pimpl->m_xmlStr += ':';
        }
        m_pimpl->m_xmlStr += localName;
        m_pimpl->m_xmlStr += "=\"";
        m_pimpl->m_writeState = StringXmlWriterImpl::WriteState_Attribute;
        break;
        }
    default:
        // TODO: Generate error
        break;
    }
}

void StringXmlWriter::WriteStartDocument()
{
    switch (m_pimpl->m_writeState)
    {
    case StringXmlWriterImpl::WriteState_Start:
        m_pimpl->m_xmlStr += "<?xml version=\"1.0\"?>";
        m_pimpl->m_writeState = StringXmlWriterImpl::WriteState_Prolog;
        break;
    default:
        // TODO: Generate error
        break;
    }
}

void StringXmlWriter::WriteStartElement(const std::string& localName)
{
    WriteStartElement(localName, "");
}

void StringXmlWriter::WriteStartElement(const std::string& localName,
                                        const std::string& ns)
{
    switch (m_pimpl->m_writeState)
    {
    case StringXmlWriterImpl::WriteState_Element:
        // An element is currently open. Close the element so we can open
        // a new one.
        m_pimpl->CloseOpenElement();
        // FALL THROUGH
    case StringXmlWriterImpl::WriteState_Content:
    case StringXmlWriterImpl::WriteState_Prolog:
    case StringXmlWriterImpl::WriteState_Start:
        {
        if (m_pimpl->m_formatting == Formatting_Indented)
        {
            m_pimpl->NewlineAndIndent();
        }

        std::string nsPrefix;
        bool mustDeclareNamespace = false;

        if (!ns.empty()) {
            nsPrefix = m_pimpl->GetExistingNamespacePrefix(ns);
            if (nsPrefix.empty()) {
                nsPrefix = m_pimpl->GetNextNamespacePrefix(ns);
                mustDeclareNamespace = true;
            }
        }

        StringXmlWriterImpl::OpenElement openElement(localName, nsPrefix);
        if (mustDeclareNamespace) {
            openElement.Namespaces[ns] = nsPrefix;
        }

        m_pimpl->m_openedElements.push_back(openElement);

        m_pimpl->m_xmlStr += '<';
        if (!nsPrefix.empty()) {
            m_pimpl->m_xmlStr += nsPrefix;
            m_pimpl->m_xmlStr += ':';
        }
        m_pimpl->m_xmlStr += localName;
        if (mustDeclareNamespace) {
            m_pimpl->m_xmlStr += " xmlns:";
            m_pimpl->m_xmlStr += nsPrefix;
            m_pimpl->m_xmlStr += "=\"";
            m_pimpl->m_xmlStr += ns;
            m_pimpl->m_xmlStr += '"';
        }

        m_pimpl->m_writeState = StringXmlWriterImpl::WriteState_Element;
        m_pimpl->m_contentWritten = false;
        break;
        }
    default:
        // TODO: Generate error
        break;
    }
}

void StringXmlWriter::WriteString(const std::string& text)
{
    switch (m_pimpl->m_writeState)
    {
    case StringXmlWriterImpl::WriteState_Attribute:
        m_pimpl->m_xmlStr += TranslateString
            (
            text,
            AttributeValueTranslations,
            ARRAYSIZE(AttributeValueTranslations)
            );
        break;
    case StringXmlWriterImpl::WriteState_Element:
        // An element is currently open. Close the element so we can start
        // writing the element content.
        m_pimpl->CloseOpenElement();
        // FALL THROUGH
    case StringXmlWriterImpl::WriteState_Content:
        m_pimpl->m_xmlStr += TranslateString
            (
            text,
            CharDataTranslations,
            ARRAYSIZE(CharDataTranslations)
            );
        m_pimpl->m_contentWritten = true;
        break;
    default:
        // TODO: Generate error
        break;
    }
}