/* Compare an input string filtered through the QP encoder to the expected output.
   We iterate over all possible split points, testing interruption of the write
   between all input characters, with zero-to-three one-character runs at the split,
   so we should single-step through all states.
   
   We then feed it back through the decoder to make sure it survives a round-trip.
 */
void MATCH(const char * in, const char * expect)
{
	int BUF_SIZE = 4096;
	char inbuf[BUF_SIZE];
	char xform[BUF_SIZE];
	char decoded[BUF_SIZE];
	int nread = 0;
	
	memset(inbuf, '\0', BUF_SIZE);
	memset(xform, '\0', BUF_SIZE);
	memset(decoded, '\0', BUF_SIZE);
	
//	printf("Testing encoding of {%s}\n", in);
	
	for (unsigned int junction = 0; junction < 4 && junction < strlen(in); junction++) {
		for (unsigned int split = 0; split < strlen(in) - junction; split++) {
		
			MojRefCountedPtr<ByteBufferOutputStream> bbos( new ByteBufferOutputStream() );
			MojRefCountedPtr<QuotedPrintableEncoderOutputStream> qpdos( new QuotedPrintableEncoderOutputStream(bbos) ) ;
	
			if (split > 0)
				qpdos->Write(in, split);
			if (junction > 0)
				qpdos->Write(in+split, 1);
			if (junction > 1)
				qpdos->Write(in+split+1, 1);
			if (junction > 2)
				qpdos->Write(in+split+2, 1);
			if (junction > 3)
				qpdos->Write(in+split+3, 1);
			if (split < strlen(in)-junction) 
				qpdos->Write(in + split + junction, strlen(in) - split - junction);
				
			qpdos->Flush();
		
			nread = bbos->ReadFromBuffer(xform, BUF_SIZE);
		
			ASSERT_EQ((int)strlen(expect), (int)nread);
			
			xform[nread] = '\0';
			
			ASSERT_STREQ(expect, std::string(xform, nread).c_str());
		}
	}
	
//	printf("Got {%s}\n", xform);

	// Take the last encoding, and try to decode it.
	MojRefCountedPtr<ByteBufferOutputStream> bbos2( new ByteBufferOutputStream() );
	MojRefCountedPtr<QuotePrintableDecoderOutputStream> qpeos( new QuotePrintableDecoderOutputStream(bbos2) ) ;
	
	qpeos->Write(xform, nread);
	qpeos->Flush();
			
	nread = bbos2->ReadFromBuffer(decoded, BUF_SIZE);

	ASSERT_EQ((int)strlen(in), (int)nread);
	ASSERT_STREQ(in, std::string(decoded, nread).c_str());
}
TEST(QuotePrintableDecoderOutputStreamTest, TestQuotePrintableDecoder)
{
	int BUF_SIZE = 100;
	char buf[BUF_SIZE];
	int nread;

	MojRefCountedPtr<ByteBufferOutputStream> bbos( new ByteBufferOutputStream() );
	QuotePrintableDecoderOutputStream qpdos(bbos);

	qpdos.Write("If you believe that truth=3Dbeauty, then surely=20=\r\nmathematics is the most beautiful branch of philosophy.", 108);
	nread = bbos->ReadFromBuffer(buf, 1024);
	ASSERT_EQ(101, (int) nread);
	ASSERT_EQ("If you believe that truth=beauty, then surely mathematics is the most beautiful branch of philosophy.", std::string(buf, 101));
}