Class: Integer

Inherits:
Object
  • Object
show all
Defined in:
(unknown)

Instance Method Summary collapse

Instance Method Details

#bencodeObject

Integer#bencode



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'ext/b_encode/b_encode.c', line 48

static VALUE
rb_integer_bencode(VALUE rb_num) {
    long num = NUM2LONG(rb_num);
    int c = 0;
    if (num == 0) {
        c = 1;
    } else {
        if (num < 0)
            c++; // minus sign
        for (int n = labs(num); n > 0; c++)
            n /= 10;
    }

    // "i"<integer>"e"
    int strlen = c + 2;
    VALUE str = rb_str_new(NULL, strlen);
    char *ptr = RSTRING_PTR(str);

    ptr[0] = 'i';
    if (num == 0) {
        ptr[1] = '0';
    } else {
        if (num < 0) {
            ptr[1] = '-';
        }
        int i = 0;
        for (int n = labs(num); n > 0; n /= 10, i++)
            ptr[c - i] = (n % 10) + '0';
    }
    ptr[c + 1] = 'e';

    return str;
}