Skip to content

Instantly share code, notes, and snippets.

@hartviglarsen
Last active February 16, 2020 10:37
Show Gist options
  • Save hartviglarsen/9f8fa6e347ab2d0da1fd38ecdea065d5 to your computer and use it in GitHub Desktop.
Save hartviglarsen/9f8fa6e347ab2d0da1fd38ecdea065d5 to your computer and use it in GitHub Desktop.
public class WhitespaceFilter : Stream
{
public WhitespaceFilter(Stream sink) => _sink = sink;
private Stream _sink;
private static readonly Regex reg = new Regex(@"(?<=[^])\t{2,}|(?<=[>])\s{2,}(?=[<])|(?<=[>])\s{2,11}(?=[<])|(?=[\n])\s{2,}");
public override bool CanRead => true;
public override bool CanSeek => true;
public override bool CanWrite => true;
public override void Flush() => _sink.Flush();
public override long Length => 0;
private long _position;
public override long Position
{
get { return _position; }
set { _position = value; }
}
public override int Read(byte[] buffer, int offset, int count)
{
return _sink.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return _sink.Seek(offset, origin);
}
public override void SetLength(long value)
{
_sink.SetLength(value);
}
public override void Close()
{
_sink.Close();
}
public override void Write(byte[] buffer, int offset, int count)
{
var data = new byte[count];
Buffer.BlockCopy(buffer, offset, data, 0, count);
var html = Encoding.Default.GetString(buffer);
html = reg.Replace(html, string.Empty);
var outdata = Encoding.Default.GetBytes(html);
_sink.Write(outdata, 0, outdata.GetLength(0));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment