Created
May 17, 2019 13:15
-
-
Save thenameless314159/91d02495c1e8da8e9124c558267f0744 to your computer and use it in GitHub Desktop.
Astron.Binary storage implementation for the CustomVar<short> provided on the wiki summary of Astron.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CustomVarInt16BinaryStorage : IBinaryStorage<CustomVar<short>> | |
{ | |
public Func<IReader, CustomVar<short>> ReadValue => reader => | |
{ | |
var result = 0; | |
for (var offset = 0; offset < 16; offset += 7) | |
{ | |
var readByte = reader.ReadValue<sbyte>(); | |
var hasNext = (readByte & 128) == 128; | |
if (offset > 0) | |
result += (readByte & sbyte.MaxValue) << offset; | |
else | |
result += (readByte & sbyte.MaxValue); | |
if (result > short.MaxValue) | |
result -= 65536; | |
if (hasNext) continue; | |
return new CustomVar<short>((short) result); | |
} | |
throw new ArgumentOutOfRangeException($"{nameof(CustomVar<short>)} from reader is invalid."); | |
}; | |
public Action<IWriter, CustomVar<short>> WriteValue => (writer, val) => | |
{ | |
var value = val.Value; | |
if (value >= sbyte.MinValue && value <= sbyte.MaxValue) | |
{ | |
writer.WriteValue((sbyte) value); | |
return; | |
} | |
var c = value & ushort.MaxValue; | |
while (c != 0) | |
{ | |
var b = c & sbyte.MaxValue; | |
c = (int) ((uint) c >> 7); | |
if (c > 0) | |
b |= 128; | |
writer.WriteValue((byte) b); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment