diff options
author | Lamont Granquist <lamont@scriptkiddie.org> | 2013-10-23 21:37:05 -0700 |
---|---|---|
committer | Lamont Granquist <lamont@scriptkiddie.org> | 2013-10-23 21:37:05 -0700 |
commit | 872073ee055ff8e72251e6483a7c4d7c1558013e (patch) | |
tree | 66a5e2937c23b239331ce46a9dd865fdc5350ab2 | |
download | ffi-yajl-872073ee055ff8e72251e6483a7c4d7c1558013e.tar.gz |
gem structure and POC library code
-rw-r--r-- | .gitignore | 28 | ||||
-rw-r--r-- | .rspec | 1 | ||||
-rw-r--r-- | Gemfile | 4 | ||||
-rw-r--r-- | LICENSE | 201 | ||||
-rw-r--r-- | README.md | 3 | ||||
-rw-r--r-- | Rakefile | 25 | ||||
-rw-r--r-- | ffi-yajl.gemspec | 23 | ||||
-rw-r--r-- | lib/ffi_yajl.rb | 261 | ||||
-rw-r--r-- | lib/ffi_yajl/json_gem.rb | 73 | ||||
-rw-r--r-- | lib/ffi_yajl/version.rb | 3 |
10 files changed, 622 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f9a64da --- /dev/null +++ b/.gitignore @@ -0,0 +1,28 @@ +*.gem +*.rake_tasks~ +*.rbc +*.swo +*.swp +*/tags +*~ +.DS_Store +.autotest +.bundle +.config +.idea +.rvmrc +.yardoc +Gemfile.lock +InstalledFiles +_yardoc +coverage +doc +doc/ +erl_crash.dump +lib/bundler/man +pkg +rdoc +spec/reports +test/tmp +test/version_tmp +tmp @@ -0,0 +1 @@ +-cbfp @@ -0,0 +1,4 @@ +source :rubygems + +gemspec :name => "ffi-yajl" + @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..f783214 --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ + +nothing yet... + diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..501ffed --- /dev/null +++ b/Rakefile @@ -0,0 +1,25 @@ +require 'rspec/core/rake_task' +require 'rubygems/package_task' + +Dir[File.expand_path("../*gemspec", __FILE__)].reverse.each do |gemspec_path| + gemspec = eval(IO.read(gemspec_path)) + Gem::PackageTask.new(gemspec).define +end + +require 'ffi_yajl/version' + +desc "Run all specs in spec directory" +RSpec::Core::RakeTask.new(:spec) do |t| + t.pattern = FileList['spec/**/*_spec.rb'] +end + +desc "Build it and ship it" +task :ship => [:clean, :gem] do + sh("git tag #{Mixlib::ShellOut::VERSION}") + sh("git push --tags") + Dir[File.expand_path("../pkg/*.gem", __FILE__)].reverse.each do |built_gem| + sh("gem push #{built_gem}") + end +end + +task :default => :spec diff --git a/ffi-yajl.gemspec b/ffi-yajl.gemspec new file mode 100644 index 0000000..39daaca --- /dev/null +++ b/ffi-yajl.gemspec @@ -0,0 +1,23 @@ +$:.unshift(File.dirname(__FILE__) + '/lib') +require 'ffi-yajl/version' + +Gem::Specification.new do |s| + s.name = 'ffi-yajl' + s.version = FFI_Yajl::VERSION + s.platform = Gem::Platform::RUBY + s.extra_rdoc_files = ["README.md", "LICENSE" ] + s.summary = "Ruby FFI wrapper around YAJL 2.x" + s.description = s.summary + s.author = "Lamont Granquist" + s.email = "lamont@scriptkiddie.org" + s.homepage = "http://github.com/lamont-granquist/ffi-yajl" + + + s.add_development_dependency "rspec", "~> 2.14" + s.add_dependency "ffi", "~> 1.9" + + s.bindir = "bin" + s.executables = [] + s.require_path = 'lib' + s.files = %w(LICENSE README.md) + Dir.glob("lib/**/*") +end diff --git a/lib/ffi_yajl.rb b/lib/ffi_yajl.rb new file mode 100644 index 0000000..b3a2914 --- /dev/null +++ b/lib/ffi_yajl.rb @@ -0,0 +1,261 @@ +require 'rubygems' +require 'ffi' + + +module FFI_Yajl + extend FFI::Library + ffi_lib 'yajl' + + class YajlCallbacks < FFI::Struct + layout :yajl_null, :pointer, + :yajl_boolean, :pointer, + :yajl_integer, :pointer, + :yajl_double, :pointer, + :yajl_number, :pointer, + :yajl_string, :pointer, + :yajl_start_map, :pointer, + :yajl_map_key, :pointer, + :yajl_end_map, :pointer, + :yajl_start_array, :pointer, + :yajl_end_array, :pointer + end + + enum :yajl_status, [ + :yajl_status_ok, + :yajl_status_client_canceled, + :yajl_status_insufficient_data, + :yajl_status_error, + ] + + enum :yajl_gen_status, [ + :yajl_gen_status_ok, + :yajl_gen_keys_must_be_strings, + :yajl_max_depth_exceeded, + :yajl_gen_in_error_state, + :yajl_gen_generation_complete, + :yajl_gen_invalid_number, + :yajl_gen_no_buf, + ] + + enum :yajl_option, [ + :yajl_allow_comments, 0x01, + :yajl_dont_validate_strings, 0x02, + :yajl_allow_trailing_garbage, 0x04, + :yajl_allow_multiple_values, 0x08, + :yajl_allow_partial_values, 0x10, + ] + + enum :yajl_gen_option, [ + :yajl_gen_beautify, 0x01, + :yajl_gen_indent_string, 0x02, + :yajl_gen_print_callback, 0x04, + :yajl_gen_validate_utf8, 0x08, + ] + + typedef :pointer, :yajl_handle + typedef :pointer, :yajl_gen + + # yajl uses unsinged char *'s consistently + typedef :pointer, :ustring_pointer + typedef :string, :ustring + + # const char *yajl_status_to_string (yajl_status code) + attach_function :yajl_status_to_string, [ :yajl_status ], :string + # yajl_handle yajl_alloc(const yajl_callbacks * callbacks, yajl_alloc_funcs * afs, void * ctx) + attach_function :yajl_alloc, [:pointer, :pointer, :pointer], :yajl_handle + # void yajl_free (yajl_handle handle) + attach_function :yajl_free, [:yajl_handle], :void + # yajl_status yajl_parse (yajl_handle hand, const unsigned char *jsonText, unsigned int jsonTextLength) + attach_function :yajl_parse, [:yajl_handle, :ustring, :uint], :yajl_status + # yajl_status yajl_parse_complete (yajl_handle hand) + attach_function :yajl_complete_parse, [:yajl_handle], :yajl_status + # unsigned char *yajl_get_error (yajl_handle hand, int verbose, const unsigned char *jsonText, unsigned int jsonTextLength) + attach_function :yajl_get_error, [:yajl_handle, :int, :ustring, :int], :ustring + # void yajl_free_error (yajl_handle hand, unsigned char *str) + attach_function :yajl_free_error, [:yajl_handle, :ustring], :void + + # + attach_function :yajl_config, [:yajl_handle, :yajl_option, :int], :int + + attach_function :yajl_gen_config, [:yajl_gen, :yajl_gen_option, :int], :int + + # yajl_gen yajl_gen_alloc (const yajl_gen_config *config, const yajl_alloc_funcs *allocFuncs) + attach_function :yajl_gen_alloc, [:pointer, :pointer], :yajl_gen + # yajl_gen yajl_gen_alloc2 (const yajl_print_t callback, const yajl_gen_config *config, const yajl_alloc_funcs *allocFuncs, void *ctx) + # attach_function :yajl_gen_alloc2, [:pointer, :pointer, :pointer, :pointer], :yajl_gen + # void yajl_gen_free (yajl_gen handle) + attach_function :yajl_gen_free, [:yajl_gen], :void + + attach_function :yajl_gen_integer, [:yajl_gen, :long], :yajl_gen_status + attach_function :yajl_gen_double, [:yajl_gen, :double], :yajl_gen_status +# attach_function :yajl_gen_number + attach_function :yajl_gen_string, [:yajl_gen, :ustring, :int], :yajl_gen_status + attach_function :yajl_gen_null, [:yajl_gen], :yajl_gen_status + attach_function :yajl_gen_bool, [:yajl_gen, :int], :yajl_gen_status + attach_function :yajl_gen_map_open, [:yajl_gen], :yajl_gen_status + attach_function :yajl_gen_map_close, [:yajl_gen], :yajl_gen_status + attach_function :yajl_gen_array_open, [:yajl_gen], :yajl_gen_status + attach_function :yajl_gen_array_close, [:yajl_gen], :yajl_gen_status + # yajl_gen_status yajl_gen_get_buf (yajl_gen hand, const unsigned char **buf, unsigned int *len) + attach_function :yajl_gen_get_buf, [:yajl_gen, :pointer ,:pointer], :yajl_gen_status + # void yajl_gen_clear (yajl_gen hand) + attach_function :yajl_gen_clear, [:yajl_gen], :void + + class ParseError < StandardError; end + class EncodeError < StandardError; end + + class Parser + class State + attr_accessor :stack, :key + def initialize + @stack = Array.new + end + + def set_value(val) + case @stack.last + when Hash + raise if key.nil? + @stack.last[@key] = val + when Array + @stack.last.push(val) + else + raise + end + end + end + + NullCallback = FFI::Function.new(:int, [:pointer]) do |ctx| + @@CTX_MAPPING[ctx.get_ulong(0)].set_value(nil) + 1 + end + BooleanCallback = FFI::Function.new(:int, [:pointer, :int]) do |ctx, boolval| + @@CTX_MAPPING[ctx.get_ulong(0)].set_value(boolval == 1 ? true : false) + 1 + end + IntegerCallback = FFI::Function.new(:int, [:pointer, :long_long]) do |ctx, intval| + @@CTX_MAPPING[ctx.get_ulong(0)].set_value(intval) + 1 + end + DoubleCallback = FFI::Function.new(:int, [:pointer, :double]) do |ctx, doubleval| + @@CTX_MAPPING[ctx.get_ulong(0)].set_value(doubleval) + 1 + end + NumberCallback = FFI::Function.new(:int, [:pointer, :pointer, :size_t]) do |ctx, numberval, numberlen| + raise "not implemented" + 1 + end + StringCallback = FFI::Function.new(:int, [:pointer, :string, :size_t]) do |ctx, stringval, stringlen| + @@CTX_MAPPING[ctx.get_ulong(0)].set_value(stringval.slice(0,stringlen)) + 1 + end + StartMapCallback = FFI::Function.new(:int, [:pointer]) do |ctx| + @@CTX_MAPPING[ctx.get_ulong(0)].stack.push(Hash.new) + 1 + end + MapKeyCallback = FFI::Function.new(:int, [:pointer, :string, :size_t]) do |ctx, key, keylen| + @@CTX_MAPPING[ctx.get_ulong(0)].key = key.slice(0,keylen) + 1 + end + EndMapCallback = FFI::Function.new(:int, [:pointer]) do |ctx| + @@CTX_MAPPING[ctx.get_ulong(0)].set_value( @@CTX_MAPPING[ctx.get_ulong(0)].stack.pop ) unless @@CTX_MAPPING[ctx.get_ulong(0)].stack.length == 1 + 1 + end + StartArrayCallback = FFI::Function.new(:int, [:pointer]) do |ctx| + @@CTX_MAPPING[ctx.get_ulong(0)].stack.push(Array.new) + 1 + end + EndArrayCallback = FFI::Function.new(:int, [:pointer]) do |ctx| + @@CTX_MAPPING[ctx.get_ulong(0)].set_value( @@CTX_MAPPING[ctx.get_ulong(0)].stack.pop ) unless @@CTX_MAPPING[ctx.get_ulong(0)].stack.length == 1 + 1 + end + + def self.parse(str, opts) + @@CTX_MAPPING ||= Hash.new + rb_ctx = FFI_Yajl::Parser::State.new() + @@CTX_MAPPING[rb_ctx.object_id] = rb_ctx + ctx = FFI::MemoryPointer.new(:long) + ctx.write_long( rb_ctx.object_id ) + callback_ptr = FFI::MemoryPointer.new(FFI_Yajl::YajlCallbacks) + callbacks = FFI_Yajl::YajlCallbacks.new(callback_ptr) + callbacks[:yajl_null] = NullCallback + callbacks[:yajl_boolean] = BooleanCallback + callbacks[:yajl_integer] = IntegerCallback + callbacks[:yajl_double] = DoubleCallback + callbacks[:yajl_number] = NumberCallback + callbacks[:yajl_string] = StringCallback + callbacks[:yajl_start_map] = StartMapCallback + callbacks[:yajl_map_key] = MapKeyCallback + callbacks[:yajl_end_map] = EndMapCallback + callbacks[:yajl_start_array] = StartArrayCallback + callbacks[:yajl_end_array] = EndArrayCallback + yajl_handle = FFI_Yajl.yajl_alloc(callback_ptr, nil, ctx) + if ( stat = FFI_Yajl.yajl_parse(yajl_handle, str, str.length)) != :yajl_status_ok + raise FFI_Yajl::ParseError.new("yajl_parse: #{stat}") + end + rb_ctx.stack.pop + ensure + FFI_Yajl.yajl_free(yajl_handle) if yajl_handle + @@CTX_MAPPING.delete(rb_ctx.object_id) if rb_ctx && rb_ctx.object_id + end + end + + class Encoder + def self.encode(obj, opts) + yajl_gen = FFI_Yajl.yajl_gen_alloc(nil, nil) + FFI_Yajl.yajl_gen_config(yajl_gen, :yajl_gen_beautify, 1); + FFI_Yajl.yajl_gen_config(yajl_gen, :yajl_gen_validate_utf8, 1); + encode_part(obj, yajl_gen) + string_ptr = FFI::MemoryPointer.new(:string) + length_ptr = FFI::MemoryPointer.new(:int) + FFI_Yajl.yajl_gen_get_buf(yajl_gen, string_ptr, length_ptr) + length = length_ptr.read_int + string = string_ptr.get_pointer(0).read_string + FFI_Yajl.yajl_gen_free(yajl_gen) + return string + end + + private + + def self.encode_part(obj, yajl_gen) + case obj + when Hash + FFI_Yajl.yajl_gen_map_open(yajl_gen) + obj.each do |key, value| + encode_part(key, yajl_gen) + encode_part(value, yajl_gen) + end + FFI_Yajl.yajl_gen_map_close(yajl_gen) + when Array + FFI_Yajl.yajl_gen_array_open(yajl_gen) + obj.each do |value| + encode_part(value, yajl_gen) + end + FFI_Yajl.yajl_gen_array_close(yajl_gen) + when NilClass + FFI_Yajl.yajl_gen_null(yajl_gen) + when TrueClass + FFI_Yajl.yajl_gen_bool(yajl_gen, 0) + when FalseClass + FFI_Yajl.yajl_gen_bool(yajl_gen, 1) + when Fixnum + FFI_Yajl.yajl_gen_integer(yajl_gen, obj) + when Bignum + raise "not implemented" + when Float + FFI_Yajl.yajl_gen_double(yajl_gen, obj) + when String + FFI_Yajl.yajl_gen_string(yajl_gen, obj, obj.length) + else + if obj.respond_to?(to_json) + # obj.to_json + raise "not implemented" + else + # obj.to_s + raise "not implemented" + end + end + end + + end +end + diff --git a/lib/ffi_yajl/json_gem.rb b/lib/ffi_yajl/json_gem.rb new file mode 100644 index 0000000..6e43cd6 --- /dev/null +++ b/lib/ffi_yajl/json_gem.rb @@ -0,0 +1,73 @@ + +# JSON compatibility layer, largely plagarized from yajl-ruby + +require 'ffi_yajl' unless defined?(FFI_Yajl::Parser) + +unless defined?(ActiveSupport) + class Object + def to_json(*args, &block) + "\"#{to_s}\"" + end + end +end + +module JSON + class JSONError < StandardError; end unless defined?(JSON::JSONError) + class GeneratorError < JSONError; end unless defined?(JSON::GeneratorError) + class ParserError < JSONError; end unless defined?(JSON::ParserError) + + def self.generate(obj, opts=nil) + #opts ||= {} + options_map = {} + #if opts.has_key?(:indent) + # options_map[:pretty] = true + # options_map[:indent] = opts[:indent] + #end + FFI_Yajl::Encoder.encode(obj, options_map) + rescue FFI_Yajl::EncodeError => e + raise JSON::GeneratorError, e.message + end + + def self.pretty_generate(obj, opts={}) + options_map = {} + #options_map[:pretty] = true + #options_map[:indent] = opts[:indent] if opts.has_key?(:indent) + FFI_Yajl::Encoder.encode(obj, options_map) + rescue FFI_Yajl::EncodeError => e + raise JSON::GeneratorError, e.message + end + + def self.dump(obj, io=nil, *args) + FFI_Yajl::Encoder.encode(obj, io) + rescue FII_Yajl::EncodeError => e + raise JSON::GeneratorError, e.message + end + + def self.default_options + #@default_options ||= {:symbolize_keys => false} + @default_options ||= {} + end + + def self.parse(str, opts=JSON.default_options) + FFI_Yajl::Parser.parse(str, opts) + rescue FFI_Yajl::ParseError => e + raise JSON::ParserError, e.message + end + + def self.load(input, *args) + FFI_Yajl::Parser.parse(input, default_options) + rescue FFI_Yajl::ParseError => e + raise JSON::ParserError, e.message + end +end + +module ::Kernel + def JSON(object, opts = {}) + if object.respond_to? :to_s + JSON.parse(object.to_s, JSON.default_options.merge(opts)) + else + JSON.generate(object,opts) + end + end +end + diff --git a/lib/ffi_yajl/version.rb b/lib/ffi_yajl/version.rb new file mode 100644 index 0000000..76e5cea --- /dev/null +++ b/lib/ffi_yajl/version.rb @@ -0,0 +1,3 @@ +class FFI_Yajl + VERSION = "0.0.1" +end |