module BigDecimal::Internal

def self.coerce_to_bigdecimal(x, prec, method_name) # :nodoc:

:nodoc:
TODO: some methods (example: BigMath.exp) require more precision than specified to coerce.
Coerce x to BigDecimal with the specified precision.
def self.coerce_to_bigdecimal(x, prec, method_name) # :nodoc:
  case x
  when BigDecimal
    return x
  when Integer, Float
    return BigDecimal(x)
  when Rational
    return BigDecimal(x, [prec, 2 * BigDecimal.double_fig].max)
  end
  raise ArgumentError, "#{x.inspect} can't be coerced into BigDecimal"
end

def self.infinity_computation_result # :nodoc:

:nodoc:
def self.infinity_computation_result # :nodoc:
  if BigDecimal.mode(BigDecimal::EXCEPTION_ALL).anybits?(BigDecimal::EXCEPTION_INFINITY)
    raise FloatDomainError, "Computation results in 'Infinity'"
  end
  BigDecimal::INFINITY
end

def self.nan_computation_result # :nodoc:

:nodoc:
def self.nan_computation_result # :nodoc:
  if BigDecimal.mode(BigDecimal::EXCEPTION_ALL).anybits?(BigDecimal::EXCEPTION_NaN)
    raise FloatDomainError, "Computation results to 'NaN'"
  end
  BigDecimal::NAN
end

def self.validate_prec(prec, method_name, accept_zero: false) # :nodoc:

:nodoc:
def self.validate_prec(prec, method_name, accept_zero: false) # :nodoc:
  raise ArgumentError, 'precision must be an Integer' unless Integer === prec
  if accept_zero
    raise ArgumentError, "Negative precision for #{method_name}" if prec < 0
  else
    raise ArgumentError, "Zero or negative precision for #{method_name}" if prec <= 0
  end
end