StringSource

From Crypto++ Wiki
Jump to: navigation, search

StringSource.png

In the Crypto++ pipelining paradigm, StringSources serve as an origin of data. It is a source that extracts data from a string type, from an ASCIIZ string, or from a buffer of bytes.

Examples

The following examples demonstrate creation of a StringSource.

StringSource ss( "Hello World" );
string data;
StringSource ss( data );

The following example demonstrates writing a string to a file.

string data;
StringSource ss( data, true /*pumpAll*/. new FileSink( "test.txt" ) );

The following example performs the same operation as above, but without the variable s.

string data;
StringSource ss( data, true /*pumpAll*/, new FileSink( "test.txt" ) );

A slightly more complicated example of pipelining is below. Before the string is written to the file, it is HexEncoded.

string s;
StringSource ss( s, true /*pumpAll*/, new HexEncoder( new FileSink( "test.txt" ) ) );

Sometimes the pipeline will be coded over multiple lines to aid in readability. The following is equivalent to the previous.

string s;
StringSource ss( s, true /*pumpAll*/,
    new HexEncoder(
        new FileSink( "test.txt" )
    ) // HexEncoder
); // StringSource

Note that the HexEncoder and FileSink created with new do not require explicit destruction - the StringSource will call delete on the HexEncoder, which in turns calls delete on the FileSink when it (the StringSource) is destroyed.

Missing Data

Its not uncommon to send data through a pipeline and then have nothing in the sink. This is usually due to the compiler matching the wrong function. For example:

string source = "ABCD...WXYZ", destination;
StringSink ss(source,
    new HexEncoder(
        new StringSink(destination)
    ) // HexEncoder
); // StringSink

After the above code executes, destination is likely to be empty because the compiler coerces the HexEncoder to a bool (the pumpAll parameter), which leaves the StringSource's attached transformation NULL. The compiler will do so without warning, even with -Wall -Wextra -Wconversion. To resolve the issue, explicitly specify the pumpAll parameter:

string source = "ABCD...WXYZ", destination;
StringSink ss(source, true /*pumpAll*/
    new HexEncoder(
        new StringSink(destination)
    ) // HexEncoder
); // StringSink