sbin/mount_hammer: Use calloc(3) and cleanups
[dragonfly.git] / contrib / gmp / mpf / ceilfloor.c
bloba0c5d77deac45fb40e03d33905378cecc9c58b11
1 /* mpf_ceil, mpf_floor -- round an mpf to an integer.
3 Copyright 2001, 2004 Free Software Foundation, Inc.
5 This file is part of the GNU MP Library.
7 The GNU MP Library is free software; you can redistribute it and/or modify
8 it under the terms of the GNU Lesser General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or (at your
10 option) any later version.
12 The GNU MP Library is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
15 License for more details.
17 You should have received a copy of the GNU Lesser General Public License
18 along with the GNU MP Library. If not, see http://www.gnu.org/licenses/. */
20 #include "gmp.h"
21 #include "gmp-impl.h"
24 /* dir==1 for ceil, dir==-1 for floor
26 Notice the use of prec+1 ensures mpf_ceil and mpf_floor are equivalent to
27 mpf_set if u is already an integer. */
29 static void __gmpf_ceil_or_floor __GMP_PROTO ((REGPARM_2_1 (mpf_ptr, mpf_srcptr, int))) REGPARM_ATTR (1);
30 #define mpf_ceil_or_floor(r,u,dir) __gmpf_ceil_or_floor (REGPARM_2_1 (r, u, dir))
32 REGPARM_ATTR (1) static void
33 mpf_ceil_or_floor (mpf_ptr r, mpf_srcptr u, int dir)
35 mp_ptr rp, up, p;
36 mp_size_t size, asize, prec;
37 mp_exp_t exp;
39 size = SIZ(u);
40 if (size == 0)
42 zero:
43 SIZ(r) = 0;
44 EXP(r) = 0;
45 return;
48 rp = PTR(r);
49 exp = EXP(u);
50 if (exp <= 0)
52 /* u is only a fraction */
53 if ((size ^ dir) < 0)
54 goto zero;
55 rp[0] = 1;
56 EXP(r) = 1;
57 SIZ(r) = dir;
58 return;
60 EXP(r) = exp;
62 up = PTR(u);
63 asize = ABS (size);
64 up += asize;
66 /* skip fraction part of u */
67 asize = MIN (asize, exp);
69 /* don't lose precision in the copy */
70 prec = PREC (r) + 1;
72 /* skip excess over target precision */
73 asize = MIN (asize, prec);
75 up -= asize;
77 if ((size ^ dir) >= 0)
79 /* rounding direction matches sign, must increment if ignored part is
80 non-zero */
81 for (p = PTR(u); p != up; p++)
83 if (*p != 0)
85 if (mpn_add_1 (rp, up, asize, CNST_LIMB(1)))
87 /* was all 0xFF..FFs, which have become zeros, giving just
88 a carry */
89 rp[0] = 1;
90 asize = 1;
91 EXP(r)++;
93 SIZ(r) = (size >= 0 ? asize : -asize);
94 return;
99 SIZ(r) = (size >= 0 ? asize : -asize);
100 if (rp != up)
101 MPN_COPY_INCR (rp, up, asize);
105 void
106 mpf_ceil (mpf_ptr r, mpf_srcptr u)
108 mpf_ceil_or_floor (r, u, 1);
111 void
112 mpf_floor (mpf_ptr r, mpf_srcptr u)
114 mpf_ceil_or_floor (r, u, -1);