Hey Yall! I'm trying to implement the "VarInt" and "VarLong" types for use with Minecraft protocol interoperability, where definitions can be found here: https://wiki.vg/Protocol#VarInt_and_VarLong
This is my current implementation of VarInt, but both VarInt and VarLong hang when trying to turn a negative number into bytes, and for some reason my breakpoints aren't working. Can anyone help debug?
#[derive(Ord, PartialOrd, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct VarInt {
value: i32,
}
impl VarInt {
pub fn new(value: i32) -> Self { Self { value } }
pub fn from_bytes(bytes: &[u8]) -> Self {
let mut result: i32 = 0;
let mut shift: u32 = 0;
let input_iter = bytes.iter();
for byte in input_iter {
result |= ((byte & 0x7f) as i32) << shift;
shift += 7;
if (byte & 0x80) == 0 {
if shift < 64 && (byte & 0x40) != 0 {
return Self {
value: result | (!0 << shift),
};
}
return Self { value: result };
}
}
Self { value: result }
}
pub fn as_bytes(&self) -> Vec<u8> {
let mut result = Vec::with_capacity(5);
let mut value = self.value as i64; // Convert to i64 to handle negative values correctly
let mut byte: u8;
loop {
byte = (value & 0x7f) as u8; // Extract the 7 least significant bits
value >>= 7; // Shift right by 7 bits
if (value == 0 && (byte & 0x40) == 0) || (value == -1 && (byte & 0x40) != 0) {
result.push(byte);
break;
} else {
result.push(byte | 0x80); // Set the most significant bit to continue the encoding
}
}
result
}
}