summaryrefslogtreecommitdiff
path: root/vendor/bundle/ruby/3.4.0/gems/eventmachine-1.2.7/lib/em/protocols/object_protocol.rb
blob: ec79cb4a6643c4de4dd633194464e5a62d3002c7 (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
module EventMachine
  module Protocols
    # ObjectProtocol allows for easy communication using marshaled ruby objects
    #
    #  module RubyServer
    #    include EM::P::ObjectProtocol
    #
    #    def receive_object obj
    #      send_object({'you said' => obj})
    #    end
    #  end
    #
    module ObjectProtocol
      # By default returns Marshal, override to return JSON or YAML, or any
      # other serializer/deserializer responding to #dump and #load.
      def serializer
        Marshal
      end

      # @private
      def receive_data data
        (@buf ||= '') << data

        while @buf.size >= 4
          if @buf.size >= 4+(size=@buf.unpack('N').first)
            @buf.slice!(0,4)
            receive_object serializer.load(@buf.slice!(0,size))
          else
            break
          end
        end
      end

      # Invoked with ruby objects received over the network
      def receive_object obj
        # stub
      end

      # Sends a ruby object over the network
      def send_object obj
        data = serializer.dump(obj)
        send_data [data.respond_to?(:bytesize) ? data.bytesize : data.size, data].pack('Na*')
      end
    end
  end
end