#include <math.h>

#include "coduo_x87emu.h" /* defines EMULATE_X87; x87 shim when it is 1 */

#include "core_math_private.h"

long double VectorLength(const vec3_t vector)
{
    float length;

#if EMULATE_X87
    /* x87-faithful transcription (stock coduo_lnxded 0x08066531): the squared sum
     * is accumulated in 80-bit (fld lane; fmul lane; faddp), the unrounded sum
     * rounded STRAIGHT to double64 for the CRT sqrt (fstpl — no float spill of the
     * sum, unlike VectorNormalize), the sqrt result narrowed to float, reloaded
     * and returned via the long-double ABI. sqrt is IEEE-mandated correctly-
     * rounded, so native sqrt(double) is bit-portable. */
    x87f ls = x87f_mul(x87f_load_f32(vector[0]), x87f_load_f32(vector[0]));
    ls = x87f_add(ls,
                  x87f_mul(x87f_load_f32(vector[1]), x87f_load_f32(vector[1])));
    ls = x87f_add(ls,
                  x87f_mul(x87f_load_f32(vector[2]), x87f_load_f32(vector[2])));
    length = (float)sqrt(x87f_store_f64(ls));
#else
    length = (float)sqrt((double)(((vector[0] * vector[0]) +
                                   (vector[1] * vector[1])) +
                                  (vector[2] * vector[2])));
#endif
    return (long double)length;
}
