Sha256: ad8c1a4a68cdaf841f32c0630c1db1166197cc46fa092280188752ba985dfdf7

Contents?: true

Size: 1.28 KB

Versions: 6

Compression:

Stored size: 1.28 KB

Contents

module Packable
  module Extensions #:nodoc:
    module Integer #:nodoc:
      def self.included(base)
        base.class_eval do
          include Packable
          extend ClassMethods
          packers do |p|
            p.set :merge_all      , :bytes=>4, :signed=>true, :endian=>:big
            p.set :default        , :long
            p.set :long           , {}
            p.set :short          , :bytes=>2
            p.set :char           , :bytes=>1, :signed=>false
            p.set :byte           , :bytes=>1
            p.set :unsigned_long  , :bytes=>4, :signed=>false
            p.set :unsigned_short , :bytes=>2, :signed=>false
          end
        end
      end

      def write_packed(io, options)
        val = self
        chars = (0...options[:bytes]).collect do
          byte = val & 0xFF
          val >>= 8
          byte.chr
        end
        chars.reverse! unless options[:endian] == :little
        io << chars.join
      end

      module ClassMethods #:nodoc:
        def unpack_string(s,options)
          s = s.reverse if options[:endian] == :little
          r = 0
          s.each_byte {|b| r = (r << 8) + b}
          r -= 1 << (8 * options[:bytes])  if options[:signed] && (1 == r >> (8 * options[:bytes] - 1))
          r
        end
      end

    end
  end
end

Version data entries

6 entries across 6 versions & 2 rubygems

Version Path
marcandre-packable-1.1.2 lib/packable/extensions/integer.rb
marcandre-packable-1.1.3 lib/packable/extensions/integer.rb
marcandre-packable-1.2.0 lib/packable/extensions/integer.rb
marcandre-packable-1.2.1 lib/packable/extensions/integer.rb
packable-1.2.0 lib/packable/extensions/integer.rb
packable-1.2.1 lib/packable/extensions/integer.rb