2 * Copyright © 2018 Intel Corporation
3 * Copyright © 2019 Valve Corporation
5 * Permission is hereby granted, free of charge, to any person obtaining a
6 * copy of this software and associated documentation files (the "Software"),
7 * to deal in the Software without restriction, including without limitation
8 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 * and/or sell copies of the Software, and to permit persons to whom the
10 * Software is furnished to do so, subject to the following conditions:
12 * The above copyright notice and this permission notice (including the next
13 * paragraph) shall be included in all copies or substantial portions of the
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
27 #include <gtest/gtest.h>
28 #include "util/fast_urem_by_const.h"
30 #define RAND_TEST_ITERATIONS 100000
33 rand_uint(unsigned min
)
35 /* Make sure we get some small and large numbers and powers of two every
40 return min
+ (rand() % 16);
42 return UINT32_MAX
- (rand() % 16);
46 r
= 1ull << (rand() % 32);
53 for (unsigned i
= 0; i
< 4; i
++)
54 r
|= ((uint32_t)rand() & 0xf) << i
* 8;
55 return r
>> (31 - (rand() % 32));
66 test_case(uint32_t n
, uint32_t d
)
69 uint64_t magic
= REMAINDER_MAGIC(d
);
70 /* Note: there's already an assert inside util_fast_urem32(), so the
71 * EXPECT_EQ is only here to make sure the test fails with a wrong result
72 * even if asserts are disabled. Ideally we could disable the assert just
73 * for the test to get a better error message, but that doesn't seem too
76 EXPECT_EQ(util_fast_urem32(n
, d
, magic
), n
% d
);
79 TEST(fast_urem_by_const
, random
)
81 for (unsigned i
= 0; i
< RAND_TEST_ITERATIONS
; i
++) {
82 uint64_t n
= rand_uint(0);
83 uint64_t d
= rand_uint(1);
88 TEST(fast_urem_by_const
, special_cases
)
91 test_case(0, UINT32_MAX
);
92 test_case(UINT32_MAX
, 1);
93 test_case(1, UINT32_MAX
);
94 test_case(UINT32_MAX
, UINT32_MAX
);
95 test_case(UINT32_MAX
, UINT32_MAX
- 1);
96 test_case(UINT32_MAX
- 1, UINT32_MAX
- 1);
97 test_case(UINT32_MAX
- 2, UINT32_MAX
- 1);