Sha256: b65d89e9d92eb72428cb9c82e31bb1ff9f36df07b2a60ddd582b6db31c276bba

Contents?: true

Size: 1.22 KB

Versions: 4

Compression:

Stored size: 1.22 KB

Contents

module Packable
  module Extensions #:nodoc:
    module Float #:nodoc:
      def self.included(base)
        base.class_eval do
          include Packable
          extend ClassMethods
          packers do |p|
            p.set :merge_all, :precision => :single, :endian => :big
            p.set :double   , :precision => :double
            p.set :float    , {}
            p.set :default  , :float
          end
        end
      end
      
      def write_packed(io, options)
        io << pack(self.class.pack_option_to_format(options))
      end

      module ClassMethods #:nodoc:
        ENDIAN_TO_FORMAT = Hash.new{|h, endian| raise ArgumentError, "Endian #{endian} is not valid. It must be one of #{h.keys.join(', ')}"}.
          merge!(:big => "G", :network => "G", :little => "E", :native => "F").freeze
          
        def pack_option_to_format(options)
          format = ENDIAN_TO_FORMAT[options[:endian]]
          format.downcase! if options[:precision] == :single
          format
        end

        def read_packed(io, options)
          io.read({:single => 4, :double => 8}[options[:precision]])   \
            .unpack(pack_option_to_format(options))   \
            .first
        end
      end
      
    end
  end
end

Version data entries

4 entries across 4 versions & 2 rubygems

Version Path
marcandre-packable-1.3.0 lib/packable/extensions/float.rb
marcandre-packable-1.3.1 lib/packable/extensions/float.rb
packable-1.3.1 lib/packable/extensions/float.rb
packable-1.3.0 lib/packable/extensions/float.rb