Skip to content

Instantly share code, notes, and snippets.

@Vincenz099
Last active March 12, 2019 10:51
Show Gist options
  • Select an option

  • Save Vincenz099/7eca93cabd388b6516ebd3213a08541a to your computer and use it in GitHub Desktop.

Select an option

Save Vincenz099/7eca93cabd388b6516ebd3213a08541a to your computer and use it in GitHub Desktop.
string compress/decompress for network
#if NETSTACK_INLINING
[MethodImpl(256)]
#endif
public BitBufferV2 AddString(string value) {
if (value == null)
throw new ArgumentNullException("value");
uint length = (uint)value.Length;
if (length > stringLengthMax)
length = stringLengthMax;
bool needsMoreThanAscii = false;
for (int i = 0; i < length; i++) {
if (value[i] > 127) {
needsMoreThanAscii = true;
break;
}
}
AddBool(needsMoreThanAscii);
Add(stringLengthBits, length);
if (needsMoreThanAscii) {
for (int i = 0; i < length; i++) {
if (value[i] > 127) {
Add(1, 1);
Add(16, value[i]);
}
else {
Add(1, 0);
Add(bitsASCII, (byte)(value[i]));
}
}
}
else {
Add(1, 0);
for (int i = 0; i < length; i++) {
Add(bitsASCII, (byte) (value[i]));
}
}
return this;
}
#if NETSTACK_INLINING
[MethodImpl(256)]
#endif
public string ReadString() {
StringBuilder builder = new StringBuilder();
bool needsMoreThanAscii = ReadBool();
uint length = Read(stringLengthBits);
if (needsMoreThanAscii) {
for (int i = 0; i < length; i++) {
var needs16 = Read(1);
if (needs16 == 1)
builder.Append((char) Read(16));
else
builder.Append((char)Read(bitsASCII));
}
}
else {
for (int i = 0; i < length; i++) {
builder.Append((char)Read(bitsASCII));
}
}
return builder.ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment