Skip to content
Myr

stb_divide.h

This file

Path

stb_divide.h

433 lines · 14.2 KiB · C

Last changed by

Merge branch 'master' into workingSean Barrettbefore adoption6e9f34d

History of this file

Take it

The walk stopped after 200 commits: lines older than aeec66c point at it.

Merge branch 'master' into workingSean Barrettbefore adoption6e9f34d

line 1why, one step back
1// stb_divide.h - v0.94 - public domain - Sean Barrett, Feb 2010

Merge branch 'randlong' of https://github.com/flibitijibibo/stb into workingSean Barrettbefore adoptionaeec66c

lines 2–5why, one step back
2// Three kinds of divide/modulus of signed integers.
3//4// HISTORY5//

Merge branch 'master' into workingSean Barrettbefore adoption6e9f34d

line 6why, one step back
6// v0.94 Fix integer overflow issues

Fix trailing whitespaceSean Barrettbefore adoption2bb4a0a

line 7why, one step back
7// v0.93 2020-02-02 Write useful exit() value from main()

update version numbersSean Barrettbefore adoptionc963e40

line 8why, one step back
8// v0.92 2019-02-25 Fix warning

Merge branch 'randlong' of https://github.com/flibitijibibo/stb into workingSean Barrettbefore adoptionaeec66c

lines 9–169why, one step back
9// v0.91 2010-02-27 Fix euclidean division by INT_MIN for non-truncating C
10// Check result with 64-bit math to catch such cases11// v0.90 2010-02-24 First public release12//13// USAGE14//15// In *ONE* source file, put:16//17// #define STB_DIVIDE_IMPLEMENTATION18// // #define C_INTEGER_DIVISION_TRUNCATES // see Note 119// // #define C_INTEGER_DIVISION_FLOORS // see Note 220// #include "stb_divide.h"21//22// Other source files should just include stb_divide.h23//24// Note 1: On platforms/compilers that you know signed C division25// truncates, you can #define C_INTEGER_DIVISION_TRUNCATES.26//27// Note 2: On platforms/compilers that you know signed C division28// floors (rounds to negative infinity), you can #define29// C_INTEGER_DIVISION_FLOORS.30//31// You can #define STB_DIVIDE_TEST in which case the implementation32// will generate a main() and compiling the result will create a33// program that tests the implementation. Run it with no arguments34// and any output indicates an error; run it with any argument and35// it will also print the test results. Define STB_DIVIDE_TEST_6436// to a 64-bit integer type to avoid overflows in the result-checking37// which give false negatives.38//39// ABOUT40//41// This file provides three different consistent divide/mod pairs42// implemented on top of arbitrary C/C++ division, including correct43// handling of overflow of intermediate calculations:44//45// trunc: a/b truncates to 0, a%b has same sign as a46// floor: a/b truncates to -inf, a%b has same sign as b47// eucl: a/b truncates to sign(b)*inf, a%b is non-negative48//49// Not necessarily optimal; I tried to keep it generally efficient,50// but there may be better ways.51//52// Briefly, for those who are not familiar with the problem, we note53// the reason these divides exist and are interesting:54//55// 'trunc' is easy to implement in hardware (strip the signs,56// compute, reapply the signs), thus is commonly defined57// by many languages (including C99)58//59// 'floor' is simple to define and better behaved than trunc;60// for example it divides integers into fixed-size buckets61// without an extra-wide bucket at 0, and for a fixed62// divisor N there are only |N| possible moduli.63//64// 'eucl' guarantees fixed-sized buckets *and* a non-negative65// modulus and defines division to be whatever is needed66// to achieve that result.67//68// See "The Euclidean definition of the functions div and mod"69// by Raymond Boute (1992), or "Division and Modulus for Computer70// Scientists" by Daan Leijen (2001)71//72// We assume of the built-in C division:73// (a) modulus is the remainder for the corresponding division74// (b) a/b truncates if a and b are the same sign75//76// Property (a) requires (a/b)*b + (a%b)==a, and is required by C.77// Property (b) seems to be true of all hardware but is *not* satisfied78// by the euclidean division operator we define, so it's possibly not79// always true. If any such platform turns up, we can add more cases.80// (Possibly only stb_div_trunc currently relies on property (b).)81//82// LICENSE83//84// See end of file for license information.858687#ifndef INCLUDE_STB_DIVIDE_H88#define INCLUDE_STB_DIVIDE_H8990#ifdef __cplusplus91extern "C" {92#endif9394extern int stb_div_trunc(int value_to_be_divided, int value_to_divide_by);95extern int stb_div_floor(int value_to_be_divided, int value_to_divide_by);96extern int stb_div_eucl (int value_to_be_divided, int value_to_divide_by);97extern int stb_mod_trunc(int value_to_be_divided, int value_to_divide_by);98extern int stb_mod_floor(int value_to_be_divided, int value_to_divide_by);99extern int stb_mod_eucl (int value_to_be_divided, int value_to_divide_by);100101#ifdef __cplusplus102}103#endif104105#ifdef STB_DIVIDE_IMPLEMENTATION106107#if defined(__STDC_VERSION) && __STDC_VERSION__ >= 19901108 #ifndef C_INTEGER_DIVISION_TRUNCATES109 #define C_INTEGER_DIVISION_TRUNCATES110 #endif111#endif112113#ifndef INT_MIN114#include <limits.h> // if you have no limits.h, #define INT_MIN yourself115#endif116117// the following macros are designed to allow testing118// other platforms by simulating them119#ifndef STB_DIVIDE_TEST_FLOOR120 #define stb__div(a,b) ((a)/(b))121 #define stb__mod(a,b) ((a)%(b))122#else123 // implement floor-style divide on trunc platform124 #ifndef C_INTEGER_DIVISION_TRUNCATES125 #error "floor test requires truncating division"126 #endif127 #undef C_INTEGER_DIVISION_TRUNCATES128 int stb__div(int v1, int v2)129 {130 int q = v1/v2, r = v1%v2;131 if ((r > 0 && v2 < 0) || (r < 0 && v2 > 0))132 return q-1;133 else134 return q;135 }136137 int stb__mod(int v1, int v2)138 {139 int r = v1%v2;140 if ((r > 0 && v2 < 0) || (r < 0 && v2 > 0))141 return r+v2;142 else143 return r;144 }145#endif146147int stb_div_trunc(int v1, int v2)148{149 #ifdef C_INTEGER_DIVISION_TRUNCATES150 return v1/v2;151 #else152 if (v1 >= 0 && v2 <= 0)153 return -stb__div(-v1,v2); // both negative to avoid overflow154 if (v1 <= 0 && v2 >= 0)155 if (v1 != INT_MIN)156 return -stb__div(v1,-v2); // both negative to avoid overflow157 else158 return -stb__div(v1+v2,-v2)-1; // push v1 away from wrap point159 else160 return v1/v2; // same sign, so expect truncation161 #endif162}163164int stb_div_floor(int v1, int v2)165{166 #ifdef C_INTEGER_DIVISION_FLOORS167 return v1/v2;168 #else169 if (v1 >= 0 && v2 < 0) {

Merge branch 'master' into workingSean Barrettbefore adoption6e9f34d

lines 170–171why, one step back
170 if (v2 + 1 >= INT_MIN + v1) // check if increasing v1's magnitude overflows
171 return -stb__div((v2+1)-v1,v2); // nope, so just compute it

Merge branch 'randlong' of https://github.com/flibitijibibo/stb into workingSean Barrettbefore adoptionaeec66c

lines 172–176why, one step back
172 else
173 return -stb__div(-v1,v2) + ((-v1)%v2 ? -1 : 0);174 }175 if (v1 < 0 && v2 >= 0) {176 if (v1 != INT_MIN) {

Merge branch 'master' into workingSean Barrettbefore adoption6e9f34d

lines 177–178why, one step back
177 if (v1 + 1 >= INT_MIN + v2) // check if increasing v1's magnitude overflows
178 return -stb__div((v1+1)-v2,-v2); // nope, so just compute it

Merge branch 'randlong' of https://github.com/flibitijibibo/stb into workingSean Barrettbefore adoptionaeec66c

lines 179–212why, one step back
179 else
180 return -stb__div(-v1,v2) + (stb__mod(v1,-v2) ? -1 : 0);181 } else // it must be possible to compute -(v1+v2) without overflowing182 return -stb__div(-(v1+v2),v2) + (stb__mod(-(v1+v2),v2) ? -2 : -1);183 } else184 return v1/v2; // same sign, so expect truncation185 #endif186}187188int stb_div_eucl(int v1, int v2)189{190 int q,r;191 #ifdef C_INTEGER_DIVISION_TRUNCATES192 q = v1/v2;193 r = v1%v2;194 #else195 // handle every quadrant separately, since we can't rely on q and r flor196 if (v1 >= 0)197 if (v2 >= 0)198 return stb__div(v1,v2);199 else if (v2 != INT_MIN)200 q = -stb__div(v1,-v2), r = stb__mod(v1,-v2);201 else202 q = 0, r = v1;203 else if (v1 != INT_MIN)204 if (v2 >= 0)205 q = -stb__div(-v1,v2), r = -stb__mod(-v1,v2);206 else if (v2 != INT_MIN)207 q = stb__div(-v1,-v2), r = -stb__mod(-v1,-v2);208 else // if v2 is INT_MIN, then we can't use -v2, but we can't divide by v2209 q = 1, r = v1-q*v2;210 else // if v1 is INT_MIN, we have to move away from overflow place211 if (v2 >= 0)212 q = -stb__div(-(v1+v2),v2)-1, r = -stb__mod(-(v1+v2),v2);

Merge branch 'master' into workingSean Barrettbefore adoption6e9f34d

line 213why, one step back
213 else if (v2 != INT_MIN)

Merge branch 'randlong' of https://github.com/flibitijibibo/stb into workingSean Barrettbefore adoptionaeec66c

line 214why, one step back
214 q = stb__div(-(v1-v2),-v2)+1, r = -stb__mod(-(v1-v2),-v2);

Merge branch 'master' into workingSean Barrettbefore adoption6e9f34d

lines 215–216why, one step back
215 else // for INT_MIN / INT_MIN, we need to be extra-careful to avoid overflow
216 q = 1, r = 0;

Merge branch 'randlong' of https://github.com/flibitijibibo/stb into workingSean Barrettbefore adoptionaeec66c

lines 217–233why, one step back
217 #endif
218 if (r >= 0)219 return q;220 else221 return q + (v2 > 0 ? -1 : 1);222}223224int stb_mod_trunc(int v1, int v2)225{226 #ifdef C_INTEGER_DIVISION_TRUNCATES227 return v1%v2;228 #else229 if (v1 >= 0) { // modulus result should always be positive230 int r = stb__mod(v1,v2);231 if (r >= 0)232 return r;233 else

Merge branch 'master' into workingSean Barrettbefore adoption6e9f34d

line 234why, one step back
234 return r - (v2 < 0 ? v2 : -v2);

Merge branch 'randlong' of https://github.com/flibitijibibo/stb into workingSean Barrettbefore adoptionaeec66c

lines 235–239why, one step back
235 } else { // modulus result should always be negative
236 int r = stb__mod(v1,v2);237 if (r <= 0)238 return r;239 else

Merge branch 'master' into workingSean Barrettbefore adoption6e9f34d

line 240why, one step back
240 return r + (v2 < 0 ? v2 : -v2);

Merge branch 'randlong' of https://github.com/flibitijibibo/stb into workingSean Barrettbefore adoptionaeec66c

lines 241–272why, one step back
241 }
242 #endif243}244245int stb_mod_floor(int v1, int v2)246{247 #ifdef C_INTEGER_DIVISION_FLOORS248 return v1%v2;249 #else250 if (v2 >= 0) { // result should always be positive251 int r = stb__mod(v1,v2);252 if (r >= 0)253 return r;254 else255 return r + v2;256 } else { // result should always be negative257 int r = stb__mod(v1,v2);258 if (r <= 0)259 return r;260 else261 return r + v2;262 }263 #endif264}265266int stb_mod_eucl(int v1, int v2)267{268 int r = stb__mod(v1,v2);269270 if (r >= 0)271 return r;272 else

Merge branch 'master' into workingSean Barrettbefore adoption6e9f34d

line 273why, one step back
273 return r - (v2 < 0 ? v2 : -v2); // negative abs() [to avoid overflow]

Merge branch 'randlong' of https://github.com/flibitijibibo/stb into workingSean Barrettbefore adoptionaeec66c

lines 274–281why, one step back
274}
275276#ifdef STB_DIVIDE_TEST277#include <stdio.h>278#include <math.h>279#include <limits.h>280281int show=0;

Merge branch 'upstream' of https://github.com/yangfl/stb into work2Sean Barrettbefore adoptiond487122

line 282why, one step back
282int err=0;

Merge branch 'randlong' of https://github.com/flibitijibibo/stb into workingSean Barrettbefore adoptionaeec66c

lines 283–285why, one step back
283
284void stbdiv_check(int q, int r, int a, int b, char *type, int dir)285{

Merge branch 'upstream' of https://github.com/yangfl/stb into work2Sean Barrettbefore adoptiond487122

line 286why, one step back
286 if ((dir > 0 && r < 0) || (dir < 0 && r > 0)) {

Merge branch 'randlong' of https://github.com/flibitijibibo/stb into workingSean Barrettbefore adoptionaeec66c

line 287why, one step back
287 fprintf(stderr, "FAILED: %s(%d,%d) remainder %d in wrong direction\n", type,a,b,r);

Merge branch 'upstream' of https://github.com/yangfl/stb into work2Sean Barrettbefore adoptiond487122

lines 288–289why, one step back
288 err++;
289 } else

Merge branch 'randlong' of https://github.com/flibitijibibo/stb into workingSean Barrettbefore adoptionaeec66c

line 290why, one step back
290 if (b != INT_MIN) // can't compute abs(), but if b==INT_MIN all remainders are valid

Merge branch 'upstream' of https://github.com/yangfl/stb into work2Sean Barrettbefore adoptiond487122

line 291why, one step back
291 if (r <= -abs(b) || r >= abs(b)) {

Merge branch 'randlong' of https://github.com/flibitijibibo/stb into workingSean Barrettbefore adoptionaeec66c

line 292why, one step back
292 fprintf(stderr, "FAILED: %s(%d,%d) remainder %d out of range\n", type,a,b,r);

Merge branch 'upstream' of https://github.com/yangfl/stb into work2Sean Barrettbefore adoptiond487122

lines 293–294why, one step back
293 err++;
294 }

Merge branch 'randlong' of https://github.com/flibitijibibo/stb into workingSean Barrettbefore adoptionaeec66c

lines 295–297why, one step back
295 #ifdef STB_DIVIDE_TEST_64
296 {297 STB_DIVIDE_TEST_64 q64 = q, r64=r, a64=a, b64=b;

Merge branch 'upstream' of https://github.com/yangfl/stb into work2Sean Barrettbefore adoptiond487122

line 298why, one step back
298 if (q64*b64+r64 != a64) {

Merge branch 'randlong' of https://github.com/flibitijibibo/stb into workingSean Barrettbefore adoptionaeec66c

line 299why, one step back
299 fprintf(stderr, "FAILED: %s(%d,%d) remainder %d doesn't match quotient %d\n", type,a,b,r,q);

Merge branch 'upstream' of https://github.com/yangfl/stb into work2Sean Barrettbefore adoptiond487122

lines 300–301why, one step back
300 err++;
301 }

Merge branch 'randlong' of https://github.com/flibitijibibo/stb into workingSean Barrettbefore adoptionaeec66c

lines 302–303why, one step back
302 }
303 #else

Merge branch 'upstream' of https://github.com/yangfl/stb into work2Sean Barrettbefore adoptiond487122

line 304why, one step back
304 if (q*b+r != a) {

Merge branch 'randlong' of https://github.com/flibitijibibo/stb into workingSean Barrettbefore adoptionaeec66c

line 305why, one step back
305 fprintf(stderr, "FAILED: %s(%d,%d) remainder %d doesn't match quotient %d\n", type,a,b,r,q);

Merge branch 'upstream' of https://github.com/yangfl/stb into work2Sean Barrettbefore adoptiond487122

lines 306–307why, one step back
306 err++;
307 }

Merge branch 'randlong' of https://github.com/flibitijibibo/stb into workingSean Barrettbefore adoptionaeec66c

lines 308–316why, one step back
308 #endif
309}310311void test(int a, int b)312{313 int q,r;314 if (show) printf("(%+11d,%+d) | ", a,b);315 q = stb_div_trunc(a,b), r = stb_mod_trunc(a,b);316 if (show) printf("(%+11d,%+2d) ", q,r); stbdiv_check(q,r,a,b, "trunc",a);

Fix trailing whitespaceSean Barrettbefore adoption2bb4a0a

line 317why, one step back
317 q = stb_div_floor(a,b), r = stb_mod_floor(a,b);

Merge branch 'randlong' of https://github.com/flibitijibibo/stb into workingSean Barrettbefore adoptionaeec66c

lines 318–386why, one step back
318 if (show) printf("(%+11d,%+2d) ", q,r); stbdiv_check(q,r,a,b, "floor",b);
319 q = stb_div_eucl (a,b), r = stb_mod_eucl (a,b);320 if (show) printf("(%+11d,%+2d)\n", q,r); stbdiv_check(q,r,a,b, "euclidean",1);321}322323void testh(int a, int b)324{325 int q,r;326 if (show) printf("(%08x,%08x) |\n", a,b);327 q = stb_div_trunc(a,b), r = stb_mod_trunc(a,b); stbdiv_check(q,r,a,b, "trunc",a);328 if (show) printf(" (%08x,%08x)", q,r);329 q = stb_div_floor(a,b), r = stb_mod_floor(a,b); stbdiv_check(q,r,a,b, "floor",b);330 if (show) printf(" (%08x,%08x)", q,r);331 q = stb_div_eucl (a,b), r = stb_mod_eucl (a,b); stbdiv_check(q,r,a,b, "euclidean",1);332 if (show) printf(" (%08x,%08x)\n ", q,r);333}334335int main(int argc, char **argv)336{337 if (argc > 1) show=1;338339 test(8,3);340 test(8,-3);341 test(-8,3);342 test(-8,-3);343 test(1,2);344 test(1,-2);345 test(-1,2);346 test(-1,-2);347 test(8,4);348 test(8,-4);349 test(-8,4);350 test(-8,-4);351352 test(INT_MAX,1);353 test(INT_MIN,1);354 test(INT_MIN+1,1);355 test(INT_MAX,-1);356 //test(INT_MIN,-1); // this traps in MSVC, so we leave it untested357 test(INT_MIN+1,-1);358 test(INT_MIN,-2);359 test(INT_MIN+1,2);360 test(INT_MIN+1,-2);361 test(INT_MAX,2);362 test(INT_MAX,-2);363 test(INT_MIN+1,2);364 test(INT_MIN+1,-2);365 test(INT_MIN,2);366 test(INT_MIN,-2);367 test(INT_MIN,7);368 test(INT_MIN,-7);369 test(INT_MIN+1,4);370 test(INT_MIN+1,-4);371372 testh(-7, INT_MIN);373 testh(-1, INT_MIN);374 testh(1, INT_MIN);375 testh(7, INT_MIN);376377 testh(INT_MAX-1, INT_MIN);378 testh(INT_MAX, INT_MIN);379 testh(INT_MIN, INT_MIN);380 testh(INT_MIN+1, INT_MIN);381382 testh(INT_MAX-1, INT_MAX);383 testh(INT_MAX , INT_MAX);384 testh(INT_MIN , INT_MAX);385 testh(INT_MIN+1, INT_MAX);386

Merge branch 'upstream' of https://github.com/yangfl/stb into work2Sean Barrettbefore adoptiond487122

line 387why, one step back
387 return err > 0 ? 1 : 0;

Merge branch 'randlong' of https://github.com/flibitijibibo/stb into workingSean Barrettbefore adoptionaeec66c

lines 388–398why, one step back
388}
389#endif // STB_DIVIDE_TEST390#endif // STB_DIVIDE_IMPLEMENTATION391#endif // INCLUDE_STB_DIVIDE_H392393/*394------------------------------------------------------------------------------395This software is available under 2 licenses -- choose whichever you prefer.396------------------------------------------------------------------------------397ALTERNATIVE A - MIT License398Copyright (c) 2017 Sean Barrett

Fix trailing whitespaceSean Barrettbefore adoption2bb4a0a

lines 399–403why, one step back
399Permission is hereby granted, free of charge, to any person obtaining a copy of
400this software and associated documentation files (the "Software"), to deal in401the Software without restriction, including without limitation the rights to402use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies403of the Software, and to permit persons to whom the Software is furnished to do

Merge branch 'randlong' of https://github.com/flibitijibibo/stb into workingSean Barrettbefore adoptionaeec66c

line 404why, one step back
404so, subject to the following conditions:

Fix trailing whitespaceSean Barrettbefore adoption2bb4a0a

line 405why, one step back
405The above copyright notice and this permission notice shall be included in all

Merge branch 'randlong' of https://github.com/flibitijibibo/stb into workingSean Barrettbefore adoptionaeec66c

line 406why, one step back
406copies or substantial portions of the Software.

Fix trailing whitespaceSean Barrettbefore adoption2bb4a0a

lines 407–412why, one step back
407THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
408IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,409FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE410AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER411LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,412OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE

Merge branch 'randlong' of https://github.com/flibitijibibo/stb into workingSean Barrettbefore adoptionaeec66c

lines 413–416why, one step back
413SOFTWARE.
414------------------------------------------------------------------------------415ALTERNATIVE B - Public Domain (www.unlicense.org)416This is free and unencumbered software released into the public domain.

Fix trailing whitespaceSean Barrettbefore adoption2bb4a0a

lines 417–418why, one step back
417Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
418software, either in source code form or as a compiled binary, for any purpose,

Merge branch 'randlong' of https://github.com/flibitijibibo/stb into workingSean Barrettbefore adoptionaeec66c

line 419why, one step back
419commercial or non-commercial, and by any means.

Fix trailing whitespaceSean Barrettbefore adoption2bb4a0a

lines 420–424why, one step back
420In jurisdictions that recognize copyright laws, the author or authors of this
421software dedicate any and all copyright interest in the software to the public422domain. We make this dedication for the benefit of the public at large and to423the detriment of our heirs and successors. We intend this dedication to be an424overt act of relinquishment in perpetuity of all present and future rights to

Merge branch 'randlong' of https://github.com/flibitijibibo/stb into workingSean Barrettbefore adoptionaeec66c

line 425why, one step back
425this software under copyright law.

Fix trailing whitespaceSean Barrettbefore adoption2bb4a0a

lines 426–430why, one step back
426THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
427IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,428FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE429AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN430ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION

Merge branch 'randlong' of https://github.com/flibitijibibo/stb into workingSean Barrettbefore adoptionaeec66c

lines 431–433why, one step back
431WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
432------------------------------------------------------------------------------433*/