summaryrefslogtreecommitdiff
path: root/lib/ffi_yajl/ext.rb
blob: bc4d410c3a9b31912e7b6b4a02bc702b47894e17 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
require 'rubygems'

require 'ffi_yajl/encoder'
require 'ffi_yajl/parser'
require 'libyajl2'
require 'ffi_yajl/map_library_name'

module FFI_Yajl
  extend FFI_Yajl::MapLibraryName

  libname = map_library_name
  libpath = File.expand_path(File.join(Libyajl2.opt_path, libname))

  #
  # FFS, what exactly was so wrong with DL.dlopen that ruby had to get rid of it???
  #

  def self.try_fiddle_dlopen(libpath)
    require 'fiddle'
    if defined?(Fiddle) && Fiddle.respond_to?(:dlopen)
      ::Fiddle.dlopen(libpath)
      true
    else
      false
    end
  rescue LoadError
    return false
  end

  def self.try_dl_dlopen(libpath)
    require 'dl'
    if defined?(DL) && DL.respond_to?(:dlopen)
      ::DL.dlopen(libpath)
      true
    else
      false
    end
  rescue LoadError
    return false
  end

  def self.try_ffi_dlopen(libpath)
    require 'ffi'
    require 'rbconfig'
    extend ::FFI::Library
    ffi_lib 'dl'
    attach_function 'dlopen', :dlopen, [:string, :int], :void
    if  RbConfig::CONFIG['host_os'] =~ /linux/i
      dlopen libpath, 0x102  # linux: RTLD_GLOBAL | RTLD_NOW
    else
      dlopen libpath, 0
    end
    true
  rescue LoadError
    return false
  end

  unless try_fiddle_dlopen(libpath) || try_dl_dlopen(libpath) || try_ffi_dlopen(libpath)
    raise "cannot find dlopen via Fiddle, DL or FFI, what am I supposed to do?"
  end

  class Parser
    require 'ffi_yajl/ext/parser'
    include FFI_Yajl::Ext::Parser
  end

  class Encoder
    require 'ffi_yajl/ext/encoder'
    include FFI_Yajl::Ext::Encoder
  end
end