Chapter 30. Quoted-printable encoding and decoding

#include <x/qp.H>

std::string s;

typedef std::back_insert_iterator<std::string> ins_iter_t;

std::string input_string;

ins_iter_t iter=std::copy(input_string.begin(), input_string.end(),
                          x::qp_encoder<ins_iter_t>(ins_iter_t(s))).eof();

The x::qp_encoder template class defines an output iterator that encodes its output sequence using quoted-printable encoding, as described in section 6.7 of RFC 4648, and writes the encoded output sequence to another output iterator, the underlying output iterator.

The template parameter is the underlying iterator class, and the constructor takes an underlying iterator class instance. After iterating over the sequence, eof() must get called to flush any remaining unencoded sequence x::qp_encoder does not often buffer anything, and generally encodes everything on the fly; but there are some edge conditions where a character gets buffered internally. eof() returns the new value of the underlying output iterator.

x::qp_encoder's constructor has three optional parameters:

class extra_encoded {

public:

    static bool encode(char c) { return c == '\'' || c == 34; }
};

typedef std::back_insert_iterator<std::string> ins_iter_t;

typedef x::qp_encoder<ins_iter_t, extra_encoded> encoder_t;

x::qp_encoder's second optional template parameter is a class with an encode() function, which returns true for any characters, in addition to control characters and non-ASCII characters that are always encoded. This is used in environments where additional characters must be encoded for syntax-related reasons. This example results in apostrophes and quote characters also getting encoded.

encode() can be a function or a class member. An instance of the traits class gets passed as the last optional parameter to x::qp_encoder's constructor, defaulting to the default constructor for the traits class.

std::string encoded;

std::string orig;

typedef std::back_insert_iterator<std::string> ins_iter_t;

typedef x::qp_decoder<ins_iter_t> decoder_t;

ins_iter_t iter=std::copy(encoded.begin(), encoded.end(),
                          decoder_t(ins_iter_t(orig))).eof();

The x::qp_decoder template class defines an output iterator that performs the opposite quoted-printable decoding, and writes the decoded output sequence to the underlying output iterator.

The template parameter is the underlying iterator class, and the constructor takes an underlying iterator class instance. After iterating over the sequence, eof() returns the new value of the underlying output iterator. x::qp_decoder does not buffer anything, so eof() has no real effect other than returning the new value of the underlying output iterator.