Sha256: 5dd45e146fa603fc5be1c84a5a4ff9b5bcf944b11530c2732c991065a14fb428

Contents?: true

Size: 1.5 KB

Versions: 2

Compression:

Stored size: 1.5 KB

Contents

# frozen_string_literal: true

require "paquito/types"
require "paquito/coder_chain"

module Paquito
  class CodecFactory
    def self.build(types, freeze: false, serializable_type: false, pool: 1)
      factory = if types.empty? && !serializable_type
        MessagePack::DefaultFactory
      else
        MessagePack::Factory.new
      end

      Types.register(factory, types) unless types.empty?
      Types.register_serializable_type(factory) if serializable_type

      if pool && pool > 0 && factory.respond_to?(:pool)
        if serializable_type || types.any? { |t| Types.recursive?(t) }
          pool *= 2
        end
        factory = factory.freeze.pool(pool, freeze: freeze)
        freeze = false
      end

      MessagePackCodec.new(factory, freeze: freeze)
    end

    class MessagePackCodec
      def initialize(factory, freeze: false)
        @factory = factory
        @freeze = freeze
      end

      def dump(object)
        @factory.dump(object)
      rescue NoMethodError => error
        raise PackError.new(error.message, error.receiver)
      rescue RangeError => error
        raise PackError, "#{error.class.name}, #{error.message}"
      end

      def load(payload)
        if @freeze
          @factory.load(payload, freeze: @freeze)
        else
          @factory.load(payload)
        end
      rescue MessagePack::UnpackError => error
        raise UnpackError, error.message
      rescue IOError => error
        raise UnpackError, "#{error.class.name}, #{error.message}"
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
paquito-0.5.0 lib/paquito/codec_factory.rb
paquito-0.4.0 lib/paquito/codec_factory.rb