Module: HashUnnest

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

Defined Under Namespace

Classes: CHnBuf, CInt

Constant Summary collapse

VERSION =
'1.0.1'.freeze

Instance Method Summary collapse

Instance Method Details

#unnestObject



4
5
6
# File 'lib/hash_unnest.rb', line 4

def unnest
  unnest_c
end

#unnest_cObject

***************************************************************************



198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'ext/hash_unnest/hash_unnest.c', line 198

static VALUE hn_unnest(VALUE self)
{
  VALUE result, in, buf, prefix;
  hn_buffer_t* c_buf = NULL;
  int size = 0;

#ifdef DEBUG
  {
    VALUE _str_self   = rb_funcall(self,   rb_intern("to_s"), 0);
    LOG("*** hn_unnest (%s)\n", StringValueCStr(_str_self));
  }
#endif

  // count leaves in input
  rb_hash_foreach(
      self,
      hn_size_closure,
      Data_Wrap_Struct(hn_int_type, NULL, NULL, &size)
  );

#ifdef DEBUG
  {
    VALUE _str_self   = rb_funcall(self,   rb_intern("to_s"), 0);
    LOG("*** size(%s): %d\n", StringValueCStr(_str_self), size);
  }
#endif

  // unnest `self` into `buf`
  prefix = rb_str_new("", 0);
  buf = hn_buffer_alloc(size);

  in = rb_ary_new2(2);
  rb_ary_store(in, 0, prefix);
  rb_ary_store(in, 1, buf);
  
  rb_hash_foreach(self, hn_unnest_closure, in);

  // sort the C array of key, value pairs
  Data_Get_Struct(buf, hn_buffer_t, c_buf);
  assert(c_buf != NULL);
  assert(c_buf->buf != NULL);
  assert(c_buf->magic == BUFFER_MAGIC);
  assert(c_buf->cursor == size);

  qsort((void*) c_buf->buf, c_buf->cursor, sizeof(hn_entry_t), hn_entry_compare);

  // copy the array into a new hash
  result = rb_hash_new();

  for (int k = 0; k < c_buf->cursor; ++k) {
    hn_entry_t entry = c_buf->buf[k];

    assert(entry.magic == RECORD_MAGIC);
    assert(entry.key != Qnil);
    assert(entry.value != Qnil);
    rb_hash_aset(result, entry.key, entry.value);
  }

  return result;
}