// Copyright © 2026 Mikhail Hogrefe
//
// This file is part of Malachite.
//
// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.

use crate::InnerFloat::{Finite, Infinity, NaN, Zero};
use crate::arithmetic::log_base_2::extended_log_base_2_of_rational;
use crate::basic::extended::ExtendedFloat;
use crate::{
    Float, emulate_float_to_float_fn, float_either_zero, float_infinity, float_nan,
    float_negative_infinity,
};
use core::cmp::Ordering::{self, *};
use malachite_base::num::arithmetic::traits::{
    CeilingLogBase2, CheckedLogBase, LogBase, LogBaseAssign,
};
use malachite_base::num::basic::floats::PrimitiveFloat;
use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::num::basic::traits::Zero as ZeroTrait;
use malachite_base::num::conversion::traits::{ExactFrom, RoundingFrom};
use malachite_base::num::factorization::traits::ExpressAsPower;
use malachite_base::num::logic::traits::SignificantBits;
use malachite_base::rounding_modes::RoundingMode::{self, *};
use malachite_nz::natural::arithmetic::float_extras::float_can_round;
use malachite_nz::platform::Limb;
use malachite_q::Rational;

// Returns `Some(log_base(x))` when it is rational, and `None` when it is irrational. The input `x`
// must be finite, positive, and not equal to 1, and `base` must be greater than 1.
//
// `log_base(x)` is rational exactly when `x` and `base` are both powers of a common rational `g`,
// say `x = g^a` and `base = g^e_base`; then `log_base(x) = a / e_base`. Taking `g` to be the
// primitive root of `base` (`base.express_as_power()`), this holds iff `x` is an integer power of
// `g` (including a negative power when `x < 1`), found by `Rational::checked_log_base`.
//
// Detecting these rational results up front is essential, not just an optimization: when the result
// is exactly representable (for example `log_9(3) = 1/2`), the Ziv loop in
// `log_base_rational_base_prec_round_normal` would never terminate, because its rounding test
// cannot resolve the ordering (less than, equal to, or greater than the representable value) of a
// result sitting exactly on a representable point or tie. That holds in every rounding mode, so
// every exactly-representable result must be caught here.
//
// Materializing `x` as a `Rational` is kept balloon-safe by capping `x`'s exponent and `base`'s
// size at `bound`, the larger of `x`'s own precision and the requested `prec`. The two can differ
// sharply -- a precision-1 `x` such as `2.0` may be asked for a 53-bit result -- so the bound must
// track `prec`, not just `x.get_prec()`; otherwise an exactly-representable result like
// `log_{2^64}(2) = 2^-6` would be missed and the Ziv loop would spin forever on it.
// (`Rational::checked_log_base` itself is balloon-safe even for a `g` near 1.)
pub(crate) fn rational_log_base_rational_base(
    x: &Float,
    base: &Rational,
    prec: u64,
) -> Option<Rational> {
    let bound = x.get_prec().unwrap().max(prec).saturating_mul(64);
    let e = i64::from(x.get_exponent().unwrap());
    if e.unsigned_abs() > bound || base.significant_bits() > bound {
        return None;
    }
    // `express_as_power` returns `None` when `base` is not a perfect power, in which case `base`
    // itself is `g` (with exponent 1).
    let (root, e_base) = base.express_as_power().unwrap_or_else(|| (base.clone(), 1));
    let a = (&Rational::exact_from(x)).checked_log_base(&root)?;
    Some(Rational::from_signeds(a, i64::exact_from(e_base)))
}

// The computation of log_base(x) for a `Rational` base is done by log_base(x) = log_2(x) /
// log_2(base). The input is finite, nonzero, and positive, and `base` is greater than 1.
//
// `log_2(base)` is computed in the extended exponent range (see `extended_log_base_2_of_rational`)
// so that a base near 1 -- where `log_2(base)` is tiny and would otherwise underflow an ordinary
// `Float`, losing the operand entirely -- is represented faithfully. The quotient is also kept
// extended, and the single conversion back to a `Float`, via `ExtendedFloat::into_float_helper`,
// performs the one correctly-rounded clamp to an infinity/maximum or zero/minimum per the rounding
// mode. Unlike an integer base, a `Rational` base allows both overflow (base near 1) and underflow
// (x near 1); both are handled by that clamp. (`log_2(x)` itself never underflows: `x` is a
// `Float`, so `|x - 1|` is at least the smallest positive `Float`, keeping `|log_2(x)|`
// representable.)
fn log_base_rational_base_prec_round_normal(
    x: &Float,
    base: &Rational,
    prec: u64,
    rm: RoundingMode,
) -> (Float, Ordering) {
    // If x is 1, the result is 0.
    if *x == 1u32 {
        return (Float::ZERO, Equal);
    }
    // If log_base(x) is rational -- x and base are both powers of a common rational -- compute it
    // directly. This includes exactly-representable results (which the Ziv loop could never
    // certify) as well as non-representable rationals (cheaper and exact this way).
    if let Some(q) = rational_log_base_rational_base(x, base, prec) {
        return Float::from_rational_prec_round(q, prec, rm);
    }
    // The result is irrational, so it is never exactly representable.
    assert_ne!(rm, Exact, "Inexact log_base_rational_base");
    // The initial slack keeps working_prec at least 7, so the working_prec - 6 below stays
    // positive.
    let mut working_prec = prec + 6 + prec.ceiling_log_base_2();
    let mut increment = Limb::WIDTH;
    loop {
        // log_2(x), correctly rounded to working_prec; finite and nonzero (x is positive and not
        // 1), and never underflowing, so the ordinary log wrapped as an ExtendedFloat suffices.
        let num = ExtendedFloat::from(x.log_base_2_prec_ref(working_prec).0);
        // log_2(base) > 0, extended (may be tiny for a base near 1).
        let den = extended_log_base_2_of_rational(base, working_prec);
        // log_2(x) / log_2(base) in the extended range; cannot overflow or underflow here.
        let (quotient, _) = num.div_prec_val_ref(&den, working_prec);
        // log_2(x) is correctly rounded (<= 1/2 ulp), log_2(base) is within 2 ulps, and the
        // division adds at most 1 more, for at most 4 ulps total; working_prec - 6 correct bits
        // comfortably suffice for the rounding test.
        if float_can_round(
            quotient.x.significand_ref().unwrap(),
            working_prec - 6,
            prec,
            rm,
        ) {
            // Round the mantissa to prec, then place the extended exponent, clamping once to the
            // Float range as the rounding mode dictates.
            let (rounded, o) = Float::from_float_prec_round(quotient.x, prec, rm);
            let mut result = ExtendedFloat::from(rounded);
            result.exp = result.exp.checked_add(quotient.exp).unwrap();
            return result.into_float_helper(prec, rm, o);
        }
        // Increase the precision.
        working_prec += increment;
        increment = working_prec >> 1;
    }
}

impl Float {
    /// Computes $\log_b x$, where $x$ is a [`Float`] and $b$ is a [`Rational`] greater than 1,
    /// rounding the result to the specified precision and with the specified rounding mode. The
    /// [`Float`] is taken by value and the base by reference. An [`Ordering`] is also returned,
    /// indicating whether the rounded value is less than, equal to, or greater than the exact
    /// value. Although `NaN`s are not comparable to any [`Float`], whenever this function returns a
    /// `NaN` it also returns `Equal`.
    ///
    /// This computes $\log_2 x / \log_2 b$, routing the base through
    /// [`Float::log_base_2_rational_prec_ref`] so that a base near 1 (where $\log_2 b$ is tiny)
    /// does not lose accuracy to cancellation.
    ///
    /// See [`RoundingMode`] for a description of the possible rounding modes.
    ///
    /// $$
    /// f(x,b,p,m) = \log_b x+\varepsilon.
    /// $$
    /// - If $\log_b x$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be
    ///   0.
    /// - If $\log_b x$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
    ///   2^{\lfloor\log_2 |\log_b x|\rfloor-p+1}$.
    /// - If $\log_b x$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
    ///   2^{\lfloor\log_2 |\log_b x|\rfloor-p}$.
    ///
    /// If the output has a precision, it is `prec`.
    ///
    /// Special cases:
    /// - $f(\text{NaN},b,p,m)=\text{NaN}$
    /// - $f(\infty,b,p,m)=\infty$
    /// - $f(-\infty,b,p,m)=\text{NaN}$
    /// - $f(\pm0.0,b,p,m)=-\infty$
    /// - $f(x,b,p,m)=\text{NaN}$ for $x<0$
    /// - $f(1.0,b,p,m)=0$
    /// - $f(x,b,p,m)=a/e$ when $x=g^a$, where $g$ is the primitive root of $b$ and $b=g^e$, rounded
    ///   to precision $p$; the result is exact if and only if $a/e$ is representable with precision
    ///   $p$ (for example $\log_4 8=3/2$ is exact)
    ///
    /// Unlike a logarithm with an integer base, this function can both overflow (for a base near 1)
    /// and underflow (for an $x$ near 1).
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
    ///
    /// # Panics
    /// Panics if `prec` is zero, if `base` is less than or equal to 1, or if `rm` is `Exact` but
    /// the result cannot be represented exactly with the given precision.
    ///
    /// # Examples
    /// ```
    /// use malachite_base::rounding_modes::RoundingMode::*;
    /// use malachite_float::Float;
    /// use malachite_q::Rational;
    /// use std::cmp::Ordering::*;
    ///
    /// let (log, o) =
    ///     Float::from(8).log_base_rational_base_prec_round(&Rational::from(4), 10, Exact);
    /// assert_eq!(log.to_string(), "1.5"); // log_4(8) = 3/2
    /// assert_eq!(o, Equal);
    ///
    /// let (log, o) =
    ///     Float::from(9).log_base_rational_base_prec_round(&Rational::from(3), 10, Exact);
    /// assert_eq!(log.to_string(), "2.0"); // log_3(9) = 2
    /// assert_eq!(o, Equal);
    /// ```
    #[inline]
    pub fn log_base_rational_base_prec_round(
        self,
        base: &Rational,
        prec: u64,
        rm: RoundingMode,
    ) -> (Self, Ordering) {
        assert_ne!(prec, 0);
        assert!(*base > 1u32, "Logarithm base must be greater than 1");
        match self {
            Self(NaN | Infinity { sign: false } | Finite { sign: false, .. }) => {
                (float_nan!(), Equal)
            }
            float_either_zero!() => (float_negative_infinity!(), Equal),
            float_infinity!() => (float_infinity!(), Equal),
            _ => log_base_rational_base_prec_round_normal(&self, base, prec, rm),
        }
    }

    /// Computes $\log_b x$, where $x$ is a [`Float`] and $b$ is a [`Rational`] greater than 1,
    /// rounding the result to the specified precision and with the specified rounding mode. The
    /// [`Float`] and the base are both taken by reference. An [`Ordering`] is also returned,
    /// indicating whether the rounded value is less than, equal to, or greater than the exact
    /// value.
    ///
    /// See [`Float::log_base_rational_base_prec_round`] for details, special cases, and a
    /// description of the rounding behavior.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
    ///
    /// # Panics
    /// Panics if `prec` is zero, if `base` is less than or equal to 1, or if `rm` is `Exact` but
    /// the result cannot be represented exactly with the given precision.
    ///
    /// # Examples
    /// ```
    /// use malachite_base::rounding_modes::RoundingMode::*;
    /// use malachite_float::Float;
    /// use malachite_q::Rational;
    /// use std::cmp::Ordering::*;
    ///
    /// let (log, o) =
    ///     (&Float::from(8)).log_base_rational_base_prec_round_ref(&Rational::from(2), 10, Exact);
    /// assert_eq!(log.to_string(), "3.0"); // log_2(8) = 3
    /// assert_eq!(o, Equal);
    ///
    /// let (log, o) =
    ///     (&Float::from(2)).log_base_rational_base_prec_round_ref(&Rational::from(4), 10, Exact);
    /// assert_eq!(log.to_string(), "0.5"); // log_4(2) = 1/2
    /// assert_eq!(o, Equal);
    /// ```
    #[inline]
    pub fn log_base_rational_base_prec_round_ref(
        &self,
        base: &Rational,
        prec: u64,
        rm: RoundingMode,
    ) -> (Self, Ordering) {
        assert_ne!(prec, 0);
        assert!(*base > 1u32, "Logarithm base must be greater than 1");
        match self {
            Self(NaN | Infinity { sign: false } | Finite { sign: false, .. }) => {
                (float_nan!(), Equal)
            }
            float_either_zero!() => (float_negative_infinity!(), Equal),
            float_infinity!() => (float_infinity!(), Equal),
            _ => log_base_rational_base_prec_round_normal(self, base, prec, rm),
        }
    }

    /// Computes $\log_b x$, where $x$ is a [`Float`] and $b$ is a [`Rational`] greater than 1,
    /// rounding the result to the nearest value of the specified precision. The [`Float`] is taken
    /// by value and the base by reference. An [`Ordering`] is also returned.
    ///
    /// See [`Float::log_base_rational_base_prec_round`] for details and special cases.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
    ///
    /// # Panics
    /// Panics if `prec` is zero or if `base` is less than or equal to 1.
    ///
    /// # Examples
    /// ```
    /// use malachite_float::Float;
    /// use malachite_q::Rational;
    /// use std::cmp::Ordering::*;
    ///
    /// let (log, o) = Float::from(8).log_base_rational_base_prec(&Rational::from(4), 10);
    /// assert_eq!(log.to_string(), "1.5"); // log_4(8) = 3/2
    /// assert_eq!(o, Equal);
    ///
    /// let (log, o) = Float::from(9).log_base_rational_base_prec(&Rational::from(3), 10);
    /// assert_eq!(log.to_string(), "2.0"); // log_3(9) = 2
    /// assert_eq!(o, Equal);
    /// ```
    #[inline]
    pub fn log_base_rational_base_prec(self, base: &Rational, prec: u64) -> (Self, Ordering) {
        self.log_base_rational_base_prec_round(base, prec, Nearest)
    }

    /// Computes $\log_b x$, where $x$ is a [`Float`] and $b$ is a [`Rational`] greater than 1,
    /// rounding the result to the nearest value of the specified precision. The [`Float`] and the
    /// base are both taken by reference. An [`Ordering`] is also returned.
    ///
    /// See [`Float::log_base_rational_base_prec_round`] for details and special cases.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
    ///
    /// # Panics
    /// Panics if `prec` is zero or if `base` is less than or equal to 1.
    ///
    /// # Examples
    /// ```
    /// use malachite_float::Float;
    /// use malachite_q::Rational;
    /// use std::cmp::Ordering::*;
    ///
    /// let (log, o) = (&Float::from(8)).log_base_rational_base_prec_ref(&Rational::from(2), 10);
    /// assert_eq!(log.to_string(), "3.0"); // log_2(8) = 3
    /// assert_eq!(o, Equal);
    ///
    /// let (log, o) = (&Float::from(2)).log_base_rational_base_prec_ref(&Rational::from(4), 10);
    /// assert_eq!(log.to_string(), "0.5"); // log_4(2) = 1/2
    /// assert_eq!(o, Equal);
    /// ```
    #[inline]
    pub fn log_base_rational_base_prec_ref(&self, base: &Rational, prec: u64) -> (Self, Ordering) {
        self.log_base_rational_base_prec_round_ref(base, prec, Nearest)
    }

    /// Computes $\log_b x$, where $x$ is a [`Float`] and $b$ is a [`Rational`] greater than 1,
    /// rounding the result to the precision of the input and with the specified rounding mode. The
    /// [`Float`] is taken by value and the base by reference. An [`Ordering`] is also returned.
    ///
    /// See [`Float::log_base_rational_base_prec_round`] for details and special cases.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is the precision of the input.
    ///
    /// # Panics
    /// Panics if `base` is less than or equal to 1, or if `rm` is `Exact` but the result cannot be
    /// represented exactly with the input's precision.
    ///
    /// # Examples
    /// ```
    /// use malachite_base::rounding_modes::RoundingMode::*;
    /// use malachite_float::Float;
    /// use malachite_q::Rational;
    /// use std::cmp::Ordering::*;
    ///
    /// let (log, o) = Float::from(9).log_base_rational_base_round(&Rational::from(3), Exact);
    /// assert_eq!(log.to_string(), "2.0"); // log_3(9) = 2
    /// assert_eq!(o, Equal);
    ///
    /// let (log, o) = Float::from(2).log_base_rational_base_round(&Rational::from(4), Exact);
    /// assert_eq!(log.to_string(), "0.5"); // log_4(2) = 1/2
    /// assert_eq!(o, Equal);
    /// ```
    #[inline]
    pub fn log_base_rational_base_round(
        self,
        base: &Rational,
        rm: RoundingMode,
    ) -> (Self, Ordering) {
        let prec = self.significant_bits();
        self.log_base_rational_base_prec_round(base, prec, rm)
    }

    /// Computes $\log_b x$, where $x$ is a [`Float`] and $b$ is a [`Rational`] greater than 1,
    /// rounding the result to the precision of the input and with the specified rounding mode. The
    /// [`Float`] and the base are both taken by reference. An [`Ordering`] is also returned.
    ///
    /// See [`Float::log_base_rational_base_prec_round`] for details and special cases.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is the precision of the input.
    ///
    /// # Panics
    /// Panics if `base` is less than or equal to 1, or if `rm` is `Exact` but the result cannot be
    /// represented exactly with the input's precision.
    ///
    /// # Examples
    /// ```
    /// use malachite_base::rounding_modes::RoundingMode::*;
    /// use malachite_float::Float;
    /// use malachite_q::Rational;
    /// use std::cmp::Ordering::*;
    ///
    /// let (log, o) =
    ///     (&Float::from(81)).log_base_rational_base_round_ref(&Rational::from(3), Exact);
    /// assert_eq!(log.to_string(), "4.0"); // log_3(81) = 4
    /// assert_eq!(o, Equal);
    ///
    /// let (log, o) =
    ///     (&Float::from(9)).log_base_rational_base_round_ref(&Rational::from(3), Exact);
    /// assert_eq!(log.to_string(), "2.0"); // log_3(9) = 2
    /// assert_eq!(o, Equal);
    /// ```
    #[inline]
    pub fn log_base_rational_base_round_ref(
        &self,
        base: &Rational,
        rm: RoundingMode,
    ) -> (Self, Ordering) {
        self.log_base_rational_base_prec_round_ref(base, self.significant_bits(), rm)
    }

    /// Computes $\log_b x$, where $x$ is a [`Float`] and $b$ is a [`Rational`] greater than 1, in
    /// place, rounding the result to the specified precision and with the specified rounding mode.
    /// The base is taken by reference. An [`Ordering`] is returned.
    ///
    /// See [`Float::log_base_rational_base_prec_round`] for details and special cases.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
    ///
    /// # Panics
    /// Panics if `prec` is zero, if `base` is less than or equal to 1, or if `rm` is `Exact` but
    /// the result cannot be represented exactly with the given precision.
    ///
    /// # Examples
    /// ```
    /// use malachite_base::rounding_modes::RoundingMode::*;
    /// use malachite_float::Float;
    /// use malachite_q::Rational;
    /// use std::cmp::Ordering::*;
    ///
    /// let mut x = Float::from(8);
    /// assert_eq!(
    ///     x.log_base_rational_base_prec_round_assign(&Rational::from(4), 10, Exact),
    ///     Equal
    /// );
    /// assert_eq!(x.to_string(), "1.5"); // log_4(8) = 3/2
    ///
    /// let mut x = Float::from(9);
    /// assert_eq!(
    ///     x.log_base_rational_base_prec_round_assign(&Rational::from(3), 10, Exact),
    ///     Equal
    /// );
    /// assert_eq!(x.to_string(), "2.0"); // log_3(9) = 2
    /// ```
    #[inline]
    pub fn log_base_rational_base_prec_round_assign(
        &mut self,
        base: &Rational,
        prec: u64,
        rm: RoundingMode,
    ) -> Ordering {
        let (result, o) = core::mem::take(self).log_base_rational_base_prec_round(base, prec, rm);
        *self = result;
        o
    }

    /// Computes $\log_b x$, where $x$ is a [`Float`] and $b$ is a [`Rational`] greater than 1, in
    /// place, rounding the result to the nearest value of the specified precision. The base is
    /// taken by reference. An [`Ordering`] is returned.
    ///
    /// See [`Float::log_base_rational_base_prec_round`] for details and special cases.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
    ///
    /// # Panics
    /// Panics if `prec` is zero or if `base` is less than or equal to 1.
    ///
    /// # Examples
    /// ```
    /// use malachite_float::Float;
    /// use malachite_q::Rational;
    ///
    /// let mut x = Float::from(8);
    /// x.log_base_rational_base_prec_assign(&Rational::from(4), 10);
    /// assert_eq!(x.to_string(), "1.5"); // log_4(8) = 3/2
    ///
    /// let mut x = Float::from(9);
    /// x.log_base_rational_base_prec_assign(&Rational::from(3), 10);
    /// assert_eq!(x.to_string(), "2.0"); // log_3(9) = 2
    /// ```
    #[inline]
    pub fn log_base_rational_base_prec_assign(&mut self, base: &Rational, prec: u64) -> Ordering {
        self.log_base_rational_base_prec_round_assign(base, prec, Nearest)
    }

    /// Computes $\log_b x$, where $x$ is a [`Float`] and $b$ is a [`Rational`] greater than 1, in
    /// place, rounding the result to the precision of the input and with the specified rounding
    /// mode. The base is taken by reference. An [`Ordering`] is returned.
    ///
    /// See [`Float::log_base_rational_base_prec_round`] for details and special cases.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is the precision of the input.
    ///
    /// # Panics
    /// Panics if `base` is less than or equal to 1, or if `rm` is `Exact` but the result cannot be
    /// represented exactly with the input's precision.
    ///
    /// # Examples
    /// ```
    /// use malachite_base::rounding_modes::RoundingMode::*;
    /// use malachite_float::Float;
    /// use malachite_q::Rational;
    ///
    /// let mut x = Float::from(9);
    /// x.log_base_rational_base_round_assign(&Rational::from(3), Exact);
    /// assert_eq!(x.to_string(), "2.0"); // log_3(9) = 2
    ///
    /// let mut x = Float::from(2);
    /// x.log_base_rational_base_round_assign(&Rational::from(4), Exact);
    /// assert_eq!(x.to_string(), "0.5"); // log_4(2) = 1/2
    /// ```
    #[inline]
    pub fn log_base_rational_base_round_assign(
        &mut self,
        base: &Rational,
        rm: RoundingMode,
    ) -> Ordering {
        let prec = self.significant_bits();
        self.log_base_rational_base_prec_round_assign(base, prec, rm)
    }
}

impl LogBase<Rational> for Float {
    type Output = Self;

    /// Computes $\log_b x$, where $x$ is a [`Float`] and $b$ is a [`Rational`] greater than 1,
    /// rounding the result to the nearest value of the input's precision. Both are taken by value.
    ///
    /// See [`Float::log_base_rational_base_prec_round`] for special cases.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is the precision of the input.
    ///
    /// # Panics
    /// Panics if `base` is less than or equal to 1.
    ///
    /// # Examples
    /// ```
    /// use malachite_base::num::arithmetic::traits::LogBase;
    /// use malachite_float::Float;
    /// use malachite_q::Rational;
    ///
    /// assert_eq!(
    ///     Float::from(2).log_base(Rational::from(4)).to_string(),
    ///     "0.5"
    /// ); // log_4(2) = 1/2
    /// assert_eq!(
    ///     Float::from(9).log_base(Rational::from(3)).to_string(),
    ///     "2.0"
    /// ); // log_3(9) = 2
    /// ```
    #[inline]
    fn log_base(self, base: Rational) -> Self {
        let prec = self.significant_bits();
        self.log_base_rational_base_prec_round(&base, prec, Nearest)
            .0
    }
}

impl LogBase<&Rational> for &Float {
    type Output = Float;

    /// Computes $\log_b x$, where $x$ is a [`Float`] and $b$ is a [`Rational`] greater than 1,
    /// rounding the result to the nearest value of the input's precision. Both are taken by
    /// reference.
    ///
    /// See [`Float::log_base_rational_base_prec_round`] for special cases.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is the precision of the input.
    ///
    /// # Panics
    /// Panics if `base` is less than or equal to 1.
    ///
    /// # Examples
    /// ```
    /// use malachite_base::num::arithmetic::traits::LogBase;
    /// use malachite_float::Float;
    /// use malachite_q::Rational;
    ///
    /// assert_eq!(
    ///     (&Float::from(81)).log_base(&Rational::from(3)).to_string(),
    ///     "4.0"
    /// ); // log_3(81) = 4
    /// assert_eq!(
    ///     (&Float::from(9)).log_base(&Rational::from(3)).to_string(),
    ///     "2.0"
    /// ); // log_3(9) = 2
    /// ```
    #[inline]
    fn log_base(self, base: &Rational) -> Float {
        self.log_base_rational_base_prec_round_ref(base, self.significant_bits(), Nearest)
            .0
    }
}

impl LogBaseAssign<&Rational> for Float {
    /// Replaces a [`Float`] $x$ with $\log_b x$, where $b$ is a [`Rational`] greater than 1,
    /// rounding the result to the nearest value of the input's precision. The base is taken by
    /// reference.
    ///
    /// See [`Float::log_base_rational_base_prec_round`] for special cases.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is the precision of the input.
    ///
    /// # Panics
    /// Panics if `base` is less than or equal to 1.
    ///
    /// # Examples
    /// ```
    /// use malachite_base::num::arithmetic::traits::LogBaseAssign;
    /// use malachite_float::Float;
    /// use malachite_q::Rational;
    ///
    /// let mut x = Float::from(81);
    /// x.log_base_assign(&Rational::from(3));
    /// assert_eq!(x.to_string(), "4.0"); // log_3(81) = 4
    ///
    /// let mut x = Float::from(9);
    /// x.log_base_assign(&Rational::from(3));
    /// assert_eq!(x.to_string(), "2.0"); // log_3(9) = 2
    /// ```
    #[inline]
    fn log_base_assign(&mut self, base: &Rational) {
        let prec = self.significant_bits();
        self.log_base_rational_base_prec_round_assign(base, prec, Nearest);
    }
}

/// Computes $\log_b x$, the base-$b$ logarithm of a primitive float, where $b$ is a [`Rational`]
/// greater than 1. Using this function is more accurate than computing the logarithm using the
/// standard library, whose logarithm functions are not always correctly rounded.
///
/// The base-$b$ logarithm of any negative number is `NaN`.
///
/// $$
/// f(x,b) = \log_b x+\varepsilon.
/// $$
/// - If $\log_b x$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
/// - If $\log_b x$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2 |\log_b
///   x|\rfloor-p}$, where $p$ is precision of the output (typically 24 if `T` is a [`f32`] and 53
///   if `T` is a [`f64`], but less if the output is subnormal).
///
/// Special cases:
/// - $f(\text{NaN},b)=\text{NaN}$
/// - $f(\infty,b)=\infty$
/// - $f(-\infty,b)=\text{NaN}$
/// - $f(\pm0.0,b)=-\infty$
/// - $f(1.0,b)=0.0$
/// - $f(x,b)=\text{NaN}$ for $x<0$
///
/// Unlike a logarithm with an integer base, this function can both overflow (for a base near 1) and
/// underflow (for an $x$ near 1).
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Panics
/// Panics if `base` is less than or equal to 1.
///
/// # Examples
/// ```
/// use malachite_base::num::basic::traits::NegativeInfinity;
/// use malachite_base::num::float::NiceFloat;
/// use malachite_float::arithmetic::log_base_rational_base::primitive_float_log_base_rational_base;
/// use malachite_q::Rational;
///
/// assert!(primitive_float_log_base_rational_base(f32::NAN, &Rational::from(10)).is_nan());
/// assert_eq!(
///     NiceFloat(primitive_float_log_base_rational_base(
///         0.0f32,
///         &Rational::from(10)
///     )),
///     NiceFloat(f32::NEGATIVE_INFINITY)
/// );
/// // log_4(8) = 3/2
/// assert_eq!(
///     NiceFloat(primitive_float_log_base_rational_base(
///         8.0f32,
///         &Rational::from(4)
///     )),
///     NiceFloat(1.5)
/// );
/// // log_(3/2)(2.25) = 2
/// assert_eq!(
///     NiceFloat(primitive_float_log_base_rational_base(
///         2.25f32,
///         &Rational::from_unsigneds(3u8, 2)
///     )),
///     NiceFloat(2.0)
/// );
/// // log_10(50)
/// assert_eq!(
///     NiceFloat(primitive_float_log_base_rational_base(
///         50.0f32,
///         &Rational::from(10)
///     )),
///     NiceFloat(1.69897)
/// );
/// assert!(primitive_float_log_base_rational_base(-1.0f32, &Rational::from(10)).is_nan());
/// ```
#[inline]
#[allow(clippy::type_repetition_in_bounds)]
pub fn primitive_float_log_base_rational_base<T: PrimitiveFloat>(x: T, base: &Rational) -> T
where
    Float: From<T> + PartialOrd<T>,
    for<'a> T: ExactFrom<&'a Float> + RoundingFrom<&'a Float>,
{
    emulate_float_to_float_fn(|x, prec| x.log_base_rational_base_prec(base, prec), x)
}
