1570af302Sopenharmony_ci#include "libm.h"
2570af302Sopenharmony_ci
3570af302Sopenharmony_cidouble nextafter(double x, double y)
4570af302Sopenharmony_ci{
5570af302Sopenharmony_ci	union {double f; uint64_t i;} ux={x}, uy={y};
6570af302Sopenharmony_ci	uint64_t ax, ay;
7570af302Sopenharmony_ci	int e;
8570af302Sopenharmony_ci
9570af302Sopenharmony_ci	if (isnan(x) || isnan(y))
10570af302Sopenharmony_ci		return x + y;
11570af302Sopenharmony_ci	if (ux.i == uy.i)
12570af302Sopenharmony_ci		return y;
13570af302Sopenharmony_ci	ax = ux.i & -1ULL/2;
14570af302Sopenharmony_ci	ay = uy.i & -1ULL/2;
15570af302Sopenharmony_ci	if (ax == 0) {
16570af302Sopenharmony_ci		if (ay == 0)
17570af302Sopenharmony_ci			return y;
18570af302Sopenharmony_ci		ux.i = (uy.i & 1ULL<<63) | 1;
19570af302Sopenharmony_ci	} else if (ax > ay || ((ux.i ^ uy.i) & 1ULL<<63))
20570af302Sopenharmony_ci		ux.i--;
21570af302Sopenharmony_ci	else
22570af302Sopenharmony_ci		ux.i++;
23570af302Sopenharmony_ci	e = ux.i >> 52 & 0x7ff;
24570af302Sopenharmony_ci	/* raise overflow if ux.f is infinite and x is finite */
25570af302Sopenharmony_ci	if (e == 0x7ff)
26570af302Sopenharmony_ci		FORCE_EVAL(x+x);
27570af302Sopenharmony_ci	/* raise underflow if ux.f is subnormal or zero */
28570af302Sopenharmony_ci	if (e == 0)
29570af302Sopenharmony_ci		FORCE_EVAL(x*x + ux.f*ux.f);
30570af302Sopenharmony_ci	return ux.f;
31570af302Sopenharmony_ci}
32