• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Protocol Buffers - Google's data interchange format
2# Copyright 2008 Google Inc.  All rights reserved.
3#
4# Use of this source code is governed by a BSD-style
5# license that can be found in the LICENSE file or at
6# https://developers.google.com/open-source/licenses/bsd
7
8# require mixins before we hook them into the java & c code
9require 'google/protobuf/message_exts'
10require 'google/protobuf/internal/object_cache'
11
12# We define these before requiring the platform-specific modules.
13# That way the module init can grab references to these.
14module Google
15  module Protobuf
16    class Error < StandardError; end
17    class ParseError < Error; end
18    class TypeError < ::TypeError; end
19
20    PREFER_FFI = case ENV['PROTOCOL_BUFFERS_RUBY_IMPLEMENTATION']
21                 when nil, "", /^native$/i
22                   false
23                 when /^ffi$/i
24                   true
25                 else
26                   warn "Unexpected value `#{ENV['PROTOCOL_BUFFERS_RUBY_IMPLEMENTATION']}` for environment variable `PROTOCOL_BUFFERS_RUBY_IMPLEMENTATION`. Should be either \"FFI\", \"NATIVE\"."
27                   false
28                 end
29
30    def self.encode(msg, options = {})
31      msg.to_proto(options)
32    end
33
34    def self.encode_json(msg, options = {})
35      msg.to_json(options)
36    end
37
38    def self.decode(klass, proto, options = {})
39      klass.decode(proto, options)
40    end
41
42    def self.decode_json(klass, json, options = {})
43      klass.decode_json(json, options)
44    end
45
46    IMPLEMENTATION = if PREFER_FFI
47      begin
48        require 'google/protobuf_ffi'
49        :FFI
50      rescue LoadError
51        warn "Caught exception `#{$!.message}` while loading FFI implementation of google/protobuf."
52        warn "Falling back to native implementation."
53        require 'google/protobuf_native'
54        :NATIVE
55      end
56    else
57      require 'google/protobuf_native'
58      :NATIVE
59    end
60  end
61end
62