xref: /freebsd/lib/libc/stdlib/imaxdiv.c (revision 7a4a63270ffd4cf0deae379b3ad32f57ea3c3e9d)
17a4a6327SMike Barcroft /*-
27a4a6327SMike Barcroft  * Copyright (c) 2001 Mike Barcroft <mike@FreeBSD.org>
37a4a6327SMike Barcroft  * All rights reserved.
47a4a6327SMike Barcroft  *
57a4a6327SMike Barcroft  * Redistribution and use in source and binary forms, with or without
67a4a6327SMike Barcroft  * modification, are permitted provided that the following conditions
77a4a6327SMike Barcroft  * are met:
87a4a6327SMike Barcroft  * 1. Redistributions of source code must retain the above copyright
97a4a6327SMike Barcroft  *    notice, this list of conditions and the following disclaimer.
107a4a6327SMike Barcroft  * 2. Redistributions in binary form must reproduce the above copyright
117a4a6327SMike Barcroft  *    notice, this list of conditions and the following disclaimer in the
127a4a6327SMike Barcroft  *    documentation and/or other materials provided with the distribution.
137a4a6327SMike Barcroft  *
147a4a6327SMike Barcroft  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
157a4a6327SMike Barcroft  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
167a4a6327SMike Barcroft  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
177a4a6327SMike Barcroft  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
187a4a6327SMike Barcroft  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
197a4a6327SMike Barcroft  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
207a4a6327SMike Barcroft  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
217a4a6327SMike Barcroft  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
227a4a6327SMike Barcroft  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
237a4a6327SMike Barcroft  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
247a4a6327SMike Barcroft  * SUCH DAMAGE.
257a4a6327SMike Barcroft  */
267a4a6327SMike Barcroft 
277a4a6327SMike Barcroft #include <sys/cdefs.h>
287a4a6327SMike Barcroft __FBSDID("$FreeBSD$");
297a4a6327SMike Barcroft 
307a4a6327SMike Barcroft #include <inttypes.h>
317a4a6327SMike Barcroft 
327a4a6327SMike Barcroft /* See comments in div.c for implementation details. */
337a4a6327SMike Barcroft imaxdiv_t
347a4a6327SMike Barcroft imaxdiv(intmax_t numer, intmax_t denom)
357a4a6327SMike Barcroft {
367a4a6327SMike Barcroft 	imaxdiv_t retval;
377a4a6327SMike Barcroft 
387a4a6327SMike Barcroft 	retval.quot = numer / denom;
397a4a6327SMike Barcroft 	retval.rem = numer % denom;
407a4a6327SMike Barcroft 	if (numer >= 0 && retval.rem < 0) {
417a4a6327SMike Barcroft 		retval.quot++;
427a4a6327SMike Barcroft 		retval.rem -= denom;
437a4a6327SMike Barcroft 	}
447a4a6327SMike Barcroft 	return (retval);
457a4a6327SMike Barcroft }
46