Method: Hash#bencode
- Defined in:
- ext/b_encode/b_encode.c
#bencode ⇒ Object
Hash#bencode
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 |
# File 'ext/b_encode/b_encode.c', line 143
static VALUE
rb_hash_bencode(VALUE hash) {
int hash_size = RHASH_SIZE(hash);
VALUE pieces[hash_size * 2];
int idx = 0;
struct foreach_info info = {&idx, pieces};
rb_hash_foreach(hash, rb_hash_bencode_entry, (VALUE) &info);
int total_len = 0;
for (int i = 0; i < hash_size * 2; i++) {
total_len += RSTRING_LEN(pieces[i]);
}
VALUE str = rb_str_new(NULL, total_len + 2);
char *ptr = RSTRING_PTR(str);
ptr[0] = 'd';
int offset = 1;
for (int i = 0; i < hash_size * 2; i++) {
int entry_len = RSTRING_LEN(pieces[i]);
memcpy(ptr + offset, RSTRING_PTR(pieces[i]), entry_len);
offset += entry_len;
}
ptr[total_len + 1] = 'e';
return str;
}
|