module FFI_Yajl::FFI::Encoder

def do_yajl_encode(obj, yajl_gen_opts, opts)

def do_yajl_encode(obj, yajl_gen_opts, opts)
  yajl_gen = FFI_Yajl.yajl_gen_alloc(nil)
  # configure the yajl encoder
  if yajl_gen_opts[:yajl_gen_beautify]
    FFI_Yajl.yajl_gen_config(yajl_gen, :yajl_gen_beautify, :int, 1)
  end
  if yajl_gen_opts[:yajl_gen_validate_utf8]
    FFI_Yajl.yajl_gen_config(yajl_gen, :yajl_gen_validate_utf8, :int, 1)
  end
  indent = yajl_gen_opts[:yajl_gen_indent_string] || " "
  FFI_Yajl.yajl_gen_config(yajl_gen, :yajl_gen_indent_string, :string, indent)
  # setup our own state
  state = {
    json_opts: opts,
    processing_key: false,
  }
  # do the encoding
  obj.ffi_yajl(yajl_gen, state)
  # get back our encoded JSON
  string_ptr = ::FFI::MemoryPointer.new(:string)
  length_ptr = ::FFI::MemoryPointer.new(:int)
  if ( status = FFI_Yajl.yajl_gen_get_buf(yajl_gen, string_ptr, length_ptr) ) != 0
    FFI_Yajl::Encoder.raise_error_for_status(status)
  end
  string = string_ptr.get_pointer(0).read_string
  FFI_Yajl.yajl_gen_free(yajl_gen)
  string
end