/*
 * Scala (https://www.scala-lang.org)
 *
 * Copyright EPFL and Lightbend, Inc.
 *
 * Licensed under Apache License 2.0
 * (http://www.apache.org/licenses/LICENSE-2.0).
 *
 * See the NOTICE file distributed with this work for
 * additional information regarding copyright ownership.
 */

package scala
package runtime

final class RichDouble(val self: Double) extends AnyVal with FractionalProxy[Double] {
  protected def num: Fractional[Double] = scala.math.Numeric.DoubleIsFractional
  protected def ord: Ordering[Double]   = scala.math.Ordering.Double.TotalOrdering

  override def doubleValue = self
  override def floatValue  = self.toFloat
  override def longValue   = self.toLong
  override def intValue    = self.toInt
  override def byteValue   = self.toByte
  override def shortValue  = self.toShort

  override def isWhole = {
    val l = self.toLong
    l.toDouble == self || l == Long.MaxValue && self < Double.PositiveInfinity || l == Long.MinValue && self > Double.NegativeInfinity
  }
  override def isValidByte  = self.toByte.toDouble == self
  override def isValidShort = self.toShort.toDouble == self
  override def isValidChar  = self.toChar.toDouble == self
  override def isValidInt   = self.toInt.toDouble == self
  // override def isValidLong = { val l = self.toLong; l.toDouble == self && l != Long.MaxValue }
  // override def isValidFloat = self.toFloat.toDouble == self
  // override def isValidDouble = !java.lang.Double.isNaN(self)

  def isNaN: Boolean         = java.lang.Double.isNaN(self)
  def isInfinity: Boolean    = java.lang.Double.isInfinite(self)
  def isFinite: Boolean      = java.lang.Double.isFinite(self)
  def isPosInfinity: Boolean = Double.PositiveInfinity == self
  def isNegInfinity: Boolean = Double.NegativeInfinity == self

  // These method are all overridden and redefined to call out to scala.math to avoid 3 allocations:
  // the primitive boxing, the value class boxing and instantiation of the Numeric num.
  // We'd like to redefine sign too but forwards binary compatibility doesn't allow us to.
  override def abs: Double               = math.abs(self)
  override def max(that: Double): Double = math.max(self, that)
  override def min(that: Double): Double = math.min(self, that)
  @deprecated("signum does not handle -0.0 or Double.NaN; use `sign` method instead", since = "2.13.0")
  override def signum: Int               = math.signum(self).toInt

  def round: Long   = math.round(self)
  def ceil: Double  = math.ceil(self)
  def floor: Double = math.floor(self)

  /** Converts an angle measured in degrees to an approximately equivalent
   *  angle measured in radians.
   *
   *  @return the measurement of the angle x in radians.
   */
  def toRadians: Double = math.toRadians(self)

  /** Converts an angle measured in radians to an approximately equivalent
   *  angle measured in degrees.
   *  @return the measurement of the angle x in degrees.
   */
  def toDegrees: Double = math.toDegrees(self)
}
