Sha256: e2f06056f024efb482d0c296b59e73ff5b78d39de1177d63f29d92786ed9286e

Contents?: true

Size: 1.21 KB

Versions: 1

Compression:

Stored size: 1.21 KB

Contents

require_relative '../format_string'

module Hexdump
  module Numeric
    #
    # @api private
    #
    # @since 1.0.0
    #
    class Decimal < FormatString

      INT_SIZE_TO_WIDTH = {
        1 => 3,  # 0xff.to_s(10).length
        2 => 5,  # 0xffff.to_s(10).length
        4 => 10, # 0xffffffff.to_s(10).length
        8 => 20  # 0xffffffffffffffff.to_s(10).length
      }

      FLOAT_SIZE_TO_WIDTH = {
        4 => 15,
        8 => 24
      }

      # @return [Integer]
      attr_reader :width

      #
      # Initializes the decimal format.
      #
      # @param [Type:Int, Type::UInt, Type::Float] type
      #
      def initialize(type)
        widths = case type
                 when Type::Float then FLOAT_SIZE_TO_WIDTH
                 else                  INT_SIZE_TO_WIDTH
                 end

        @width = widths.fetch(type.size) do
          raise(NotImplementedError,"type #{type} with unsupported size #{type.size}")
        end

        case type
        when Type::Float
          super("% #{@width}g"); @width += 1
        else
          if type.signed?
            super("% #{@width}d"); @width += 1
          else
            super("%#{@width}d")
          end
        end
      end

    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
hexdump-1.0.1 lib/hexdump/numeric/decimal.rb