1//
2// QuotedPrintableEncoder.cpp
3//
4// Library: Net
5// Package: Messages
6// Module: QuotedPrintableEncoder
7//
8// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
9// and Contributors.
10//
11// SPDX-License-Identifier: BSL-1.0
12//
13
14
15#include "Poco/Net/QuotedPrintableEncoder.h"
16#include "Poco/NumberFormatter.h"
17
18
19using Poco::UnbufferedStreamBuf;
20using Poco::NumberFormatter;
21
22
23namespace Poco {
24namespace Net {
25
26
27QuotedPrintableEncoderBuf::QuotedPrintableEncoderBuf(std::ostream& ostr):
28 _pending(-1),
29 _lineLength(0),
30 _ostr(ostr)
31{
32}
33
34
35QuotedPrintableEncoderBuf::~QuotedPrintableEncoderBuf()
36{
37 try
38 {
39 close();
40 }
41 catch (...)
42 {
43 }
44}
45
46
47int QuotedPrintableEncoderBuf::writeToDevice(char c)
48{
49 if (_pending != -1)
50 {
51 if (_pending == '\r' && c == '\n')
52 writeRaw((char) _pending);
53 else if (c == '\r' || c == '\n')
54 writeEncoded((char) _pending);
55 else
56 writeRaw((char) _pending);
57 _pending = -1;
58 }
59 if (c == '\t' || c == ' ')
60 {
61 _pending = charToInt(c);
62 return _pending;
63 }
64 else if (c == '\r' || c == '\n' || (c > 32 && c < 127 && c != '='))
65 {
66 writeRaw(c);
67 }
68 else
69 {
70 writeEncoded(c);
71 }
72 return charToInt(c);
73}
74
75
76void QuotedPrintableEncoderBuf::writeEncoded(char c)
77{
78 if (_lineLength >= 73)
79 {
80 _ostr << "=\r\n";
81 _lineLength = 3;
82 }
83 else _lineLength += 3;
84 _ostr << '=' << NumberFormatter::formatHex((unsigned) charToInt(c), 2);
85}
86
87
88void QuotedPrintableEncoderBuf::writeRaw(char c)
89{
90 if (c == '\r' || c == '\n')
91 {
92 _ostr.put(c);
93 _lineLength = 0;
94 }
95 else if (_lineLength < 75)
96 {
97 _ostr.put(c);
98 ++_lineLength;
99 }
100 else
101 {
102 _ostr << "=\r\n" << c;
103 _lineLength = 1;
104 }
105}
106
107
108int QuotedPrintableEncoderBuf::close()
109{
110 sync();
111 return _ostr ? 0 : -1;
112}
113
114
115QuotedPrintableEncoderIOS::QuotedPrintableEncoderIOS(std::ostream& ostr): _buf(ostr)
116{
117 poco_ios_init(&_buf);
118}
119
120
121QuotedPrintableEncoderIOS::~QuotedPrintableEncoderIOS()
122{
123}
124
125
126int QuotedPrintableEncoderIOS::close()
127{
128 return _buf.close();
129}
130
131
132QuotedPrintableEncoderBuf* QuotedPrintableEncoderIOS::rdbuf()
133{
134 return &_buf;
135}
136
137
138QuotedPrintableEncoder::QuotedPrintableEncoder(std::ostream& ostr):
139 QuotedPrintableEncoderIOS(ostr),
140 std::ostream(&_buf)
141{
142}
143
144
145QuotedPrintableEncoder::~QuotedPrintableEncoder()
146{
147}
148
149
150} } // namespace Poco::Net
151