Module: Varint

Defined in:
lib/varint/version.rb,
ext/varint/varint.c

Constant Summary collapse

VERSION =
"0.1.1"

Instance Method Summary collapse

Instance Method Details

#decode(io) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'ext/varint/varint.c', line 23

static VALUE varint_decode(VALUE module, VALUE io)
{
    unsigned long long int_val = 0;
    unsigned shift = 0;
    unsigned char byte;

    while (1) {
        if (shift >= 64) {
            rb_raise(rb_eArgError, "too many bytes when decoding varint");
        }
        byte = (unsigned char)NUM2INT(rb_funcall(io, getbyte, 0));
        int_val |= ((unsigned long long)(byte & 0x7f)) << shift;
        shift += 7;
        if ((byte & 0x80) == 0) {
            return ULL2NUM(int_val);
        }
    }
}

#encode(io, int_valV) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'ext/varint/varint.c', line 6

static VALUE varint_encode(VALUE module, VALUE io, VALUE int_valV)
{
    /* unsigned for the bit shifting ops */
    unsigned long long int_val = NUM2ULL(int_valV);
    unsigned char byte;
    while (1) {
        byte = int_val & 0x7f;
        int_val >>= 7;
        if (int_val == 0) {
            rb_funcall(io, putbyte, 1, INT2NUM(byte));
            return Qnil;
        } else {
            rb_funcall(io, putbyte, 1, INT2NUM(byte | 0x80));
        }
    }
}