lib/varint: Add toVarN() functions

windows
BodgeMaster 2022-12-20 04:41:09 +01:00
parent 26df433dc5
commit 7108e71b96
2 changed files with 129 additions and 0 deletions

View File

@ -83,4 +83,57 @@ namespace VarInt {
return ErrorOr<int64_t>(returnValue); return ErrorOr<int64_t>(returnValue);
} }
// appends to the vector
void toVar32(int32_t value, std::vector<uint8_t> &data) {
uint8_t nextByte;
uint8_t shift = 0;
// do something else after the 4th shift
while (shift < 4) {
if (shift>0 && value==0) {
return;
}
nextByte = value & 0b01111111;
value = (value >> 7) & 0x01FFFFFF;
shift++;
if (value>0) {
nextByte = nextByte + 0b10000000;
}
data.push_back(nextByte);
}
if (value>0) {
data.push_back(value & 0b00001111);
}
}
// appends to the vector
void toVar64(int64_t value, std::vector<uint8_t> &data) {
uint8_t nextByte;
uint8_t shift = 0;
// do something else after the 4th shift
while (shift < 9) {
if (shift>0 && value==0) {
return;
}
nextByte = value & 0b01111111;
value = (value >> 7) & 0x01FFFFFFFFFFFFFF;
shift++;
if (value>0) {
nextByte = nextByte + 0b10000000;
}
data.push_back(nextByte);
}
if (value>0) {
data.push_back(value & 0b00000001);
}
}
} }

View File

@ -158,6 +158,82 @@ int main() {
std::cout << "Passed fromVar64 test." << std::endl; std::cout << "Passed fromVar64 test." << std::endl;
// reversing all the previous tests
std::vector<uint8_t> dataDump;
VarInt::toVar32(0, dataDump);
ASSERT(dataDump[0] == 0);
VarInt::toVar32(-1, dataDump);
ASSERT(
dataDump[1]==255 &&
dataDump[2]==255 &&
dataDump[3]==255 &&
dataDump[4]==255 &&
dataDump[5]==15
);
VarInt::toVar32(4369, dataDump);
ASSERT(
dataDump[6]==0b10010001 &&
dataDump[7]==0b00100010
);
VarInt::toVar32(2375101, dataDump);
ASSERT(
dataDump[8]==0b10111101 &&
dataDump[9]==0b11111011 &&
dataDump[10]==0b10010000 &&
dataDump[11]==0b00000001
);
std::cout << "Passed toVar32 test." << std::endl;
VarInt::toVar64(0, dataDump);
ASSERT(dataDump[12]==0);
VarInt::toVar64(-1, dataDump);
ASSERT(
dataDump[13]==255 &&
dataDump[14]==255 &&
dataDump[15]==255 &&
dataDump[16]==255 &&
dataDump[17]==255 &&
dataDump[18]==255 &&
dataDump[19]==255 &&
dataDump[20]==255 &&
dataDump[21]==255 &&
dataDump[22]==1
);
VarInt::toVar64(2310347307446489235, dataDump);
ASSERT(
dataDump[23]==0b10010011 &&
dataDump[24]==0b10100001 &&
dataDump[25]==0b10000011 &&
dataDump[26]==0b11000001 &&
dataDump[27]==0b10101010 &&
dataDump[28]==0b10010100 &&
dataDump[29]==0b10000000 &&
dataDump[30]==0b10001000 &&
dataDump[31]==0b00100000
);
VarInt::toVar64(-9205322385119247871, dataDump);
ASSERT(
dataDump[32]==0b10000001 &&
dataDump[33]==0b10000100 &&
dataDump[34]==0b10010000 &&
dataDump[35]==0b11000000 &&
dataDump[36]==0b10000000 &&
dataDump[37]==0b10000010 &&
dataDump[38]==0b10001000 &&
dataDump[39]==0b10100000 &&
dataDump[40]==0b10000000 &&
dataDump[41]==0b00000001
)
std::cout << "Passed toVar64 test." << std::endl;
return 0; return 0;
} }