Skip to content

Instantly share code, notes, and snippets.

@ayende
Last active October 11, 2019 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ayende/e3c3bd099afb39da16c65d001ca5c819 to your computer and use it in GitHub Desktop.
Save ayende/e3c3bd099afb39da16c65d001ca5c819 to your computer and use it in GitHub Desktop.
public class DiffBinaryWriter : BinaryWriter
{
long prev;
public DiffBinaryWriter(Stream s, long start) : base(s)
{
prev = start;
WriteValue(prev);
}
public void Diff(long cur)
{
var diff = cur - prev;
prev = cur;
if (diff <= 0)
throw new ArgumentOutOfRangeException($"{cur} is not greater than {prev}, values aren't sorted");
WriteValue(diff);
}
private void WriteValue(long diff)
{
if (diff > int.MaxValue)
{
// probably rare
Write7BitEncodedInt(0); // indicate that we need to read a full long here
Write(diff);
return;
}
Write7BitEncodedInt((int)diff);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment