Last active
March 12, 2019 10:51
-
-
Save Vincenz099/7eca93cabd388b6516ebd3213a08541a to your computer and use it in GitHub Desktop.
string compress/decompress for network
This file contains hidden or 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
| #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