2010-05-19 14:17:06 -04:00
|
|
|
package com.fsck.k9.mail.filter;
|
2008-11-01 17:32:06 -04:00
|
|
|
|
|
|
|
import java.io.FilterOutputStream;
|
|
|
|
import java.io.IOException;
|
|
|
|
import java.io.OutputStream;
|
|
|
|
|
2011-02-06 17:09:48 -05:00
|
|
|
public class EOLConvertingOutputStream extends FilterOutputStream {
|
2014-12-16 19:08:51 -05:00
|
|
|
private static final int CR = '\r';
|
|
|
|
private static final int LF = '\n';
|
2010-02-04 21:36:52 -05:00
|
|
|
private int lastChar;
|
2014-12-16 19:08:51 -05:00
|
|
|
private static final int IGNORE_LF = Integer.MIN_VALUE;
|
|
|
|
|
2008-11-01 17:32:06 -04:00
|
|
|
|
2011-02-06 17:09:48 -05:00
|
|
|
public EOLConvertingOutputStream(OutputStream out) {
|
2008-11-01 17:32:06 -04:00
|
|
|
super(out);
|
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
2011-02-06 17:09:48 -05:00
|
|
|
public void write(int oneByte) throws IOException {
|
2014-12-16 19:08:51 -05:00
|
|
|
if (oneByte == LF && lastChar == IGNORE_LF) {
|
|
|
|
lastChar = LF;
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (oneByte == LF && lastChar != CR) {
|
|
|
|
super.write(CR);
|
|
|
|
} else if (oneByte != LF && lastChar == CR) {
|
|
|
|
super.write(LF);
|
2008-11-01 17:32:06 -04:00
|
|
|
}
|
2014-12-16 19:08:51 -05:00
|
|
|
super.write(oneByte);
|
|
|
|
lastChar = oneByte;
|
2008-11-01 17:32:06 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
2011-02-06 17:09:48 -05:00
|
|
|
public void flush() throws IOException {
|
2014-12-16 19:08:51 -05:00
|
|
|
if (lastChar == CR) {
|
|
|
|
super.write(LF);
|
2010-02-04 21:36:52 -05:00
|
|
|
// We have to ignore the next character if it is <LF>. Otherwise it
|
|
|
|
// will be expanded to an additional <CR><LF> sequence although it
|
|
|
|
// belongs to the one just completed.
|
2014-12-16 19:08:51 -05:00
|
|
|
lastChar = IGNORE_LF;
|
2008-11-01 17:32:06 -04:00
|
|
|
}
|
|
|
|
super.flush();
|
|
|
|
}
|
|
|
|
}
|