Last active
November 14, 2018 07:17
-
-
Save Beeblerox/0e13a4c93d9cf9493ee3b710e38cae65 to your computer and use it in GitHub Desktop.
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
import haxe.io.Bytes; | |
/** | |
* See following links for explanations: | |
* https://habr.com/post/350796/ | |
* https://github.com/stoklund/varint/blob/master/leb128.cpp | |
* You could also google for "msb varint" | |
* | |
* Usage example: | |
* | |
var ints = [10, 100, 1000, 10000, 1000000, 10000000]; | |
var bytes = ArrayEncoderDecoder.encodeArray(ints); | |
var decoded = ArrayEncoderDecoder.decodeArray(bytes); | |
trace(ints); | |
trace(decoded); | |
trace(bytes.length); | |
* | |
*/ | |
class ArrayEncoderDecoder | |
{ | |
private static function encodeVarint(x:UInt, to:Array<Int>):Void | |
{ | |
while (x > 127) | |
{ | |
to.push((x | 0x80)); | |
x >>= 7; | |
} | |
to.push(x); | |
} | |
public static function encodeArray(array:Array<Int>):Bytes | |
{ | |
var temp = new Array<Int>(); | |
for (i in 0...array.length) | |
{ | |
encodeVarint(array[i], temp); | |
} | |
var result = Bytes.alloc(temp.length); | |
for (i in 0...temp.length) | |
{ | |
result.set(i, temp[i]); | |
} | |
return result; | |
} | |
public static function decodeArray(bytes:Bytes):Array<Int> | |
{ | |
var result = new Array<Int>(); | |
var n:Int = 0; | |
while (n < bytes.length) | |
{ | |
var byte:Int = bytes.get(n); | |
n++; | |
if (byte < 128) | |
{ | |
result.push(byte); | |
continue; | |
} | |
var value:Int = byte & 0x7f; | |
var shift:Int = 7; | |
do { | |
byte = bytes.get(n); | |
n++; | |
value |= (byte & 0x7f) << shift; | |
shift += 7; | |
} while (byte >= 128); | |
result.push(value); | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment