Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

VarInt support #45

Open
soanvig opened this issue Apr 29, 2022 · 3 comments · May be fixed by #47
Open

VarInt support #45

soanvig opened this issue Apr 29, 2022 · 3 comments · May be fixed by #47

Comments

@soanvig
Copy link

soanvig commented Apr 29, 2022

Hey! One thing I'm missing is VarInt support. I currently implemented support for this as follows using varint library. It does not comply to current code standards, and I had no time to adapt to them - that's why I wrote this dirty implementation and no PR.

Also, your readOffset is private (not protected) so I cannot easily extend, thus as any cast in read function.

WDYT about adding support for that style of integers into SmartBuffer?

export class SmartBuffer extends OriginalSmartBuffer {

  /** @TODO add tests */
  public writeVarInt (int: number): SmartBuffer {
    const INT = Math.pow(2, 31);
    const MSB = 0x80;
    const REST = 0x7F;
    const MSBALL = ~REST;

    if (int > Number.MAX_SAFE_INTEGER) {
      throw new RangeError('Could not encode varint');
    }

    const out = [];
    let offset = 0;

    while (int >= INT) {
      out[offset++] = (int & 0xFF) | MSB;
      int /= 128;
    }
    while (int & MSBALL) {
      out[offset++] = (int & 0xFF) | MSB;
      int >>>= 7;
    }
    out[offset] = int | 0;

    this.writeBuffer(Buffer.from(out));

    return this;
  }

  /** @TODO add tests */
  public readVarInt (): number {
    const MSB = 0x80;
    const REST = 0x7F;

    let res = 0;
    let shift = 0;
    let counter = 0;
    let b;
    const buffer = (this as any)._buff;

    do {
      if (shift > 49) {
        throw new RangeError('Could not decode varint');
      }
      b = buffer[this.readOffset + counter];
      counter += 1;
      res += shift < 28
        ? (b & REST) << shift
        : (b & REST) * Math.pow(2, shift);
      shift += 7;
    } while (b >= MSB);

    this.readOffset += counter;

    return res;
  };
}
@JoshGlazebrook
Copy link
Owner

I don't see why not. Do you have time to make a PR?

@soanvig
Copy link
Author

soanvig commented May 3, 2022

Yeah, I think I can do that. I've already battle-tested my implementation on Minecraft server protocol, and I'm positive it works correctly.

Will post soon

@soanvig soanvig linked a pull request May 3, 2022 that will close this issue
@soanvig
Copy link
Author

soanvig commented May 3, 2022

@JoshGlazebrook probably done, not sure though
#47

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants