1 // Copyright 2024 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14
15 #include "pw_allocator/fragmentation.h"
16
17 #include <cstddef>
18
19 #include "pw_unit_test/framework.h"
20
21 namespace {
22
23 using ::pw::allocator::Fragmentation;
24
TEST(FragmentationTest,ValuesAreCorrect)25 TEST(FragmentationTest, ValuesAreCorrect) {
26 Fragmentation fragmentation;
27 fragmentation.AddFragment(867);
28 fragmentation.AddFragment(5309);
29 EXPECT_EQ(fragmentation.sum_of_squares.hi, 0U);
30 EXPECT_EQ(fragmentation.sum_of_squares.lo, 867U * 867U + 5309U * 5309U);
31 EXPECT_EQ(fragmentation.sum, 867U + 5309U);
32 }
33
TEST(FragmentationTest,HandlesOverflow)34 TEST(FragmentationTest, HandlesOverflow) {
35 constexpr size_t kHalfWord = size_t(1) << sizeof(size_t) * 4;
36 Fragmentation fragmentation;
37 fragmentation.AddFragment(kHalfWord);
38 fragmentation.AddFragment(kHalfWord);
39 fragmentation.AddFragment(kHalfWord);
40 fragmentation.AddFragment(kHalfWord);
41 EXPECT_EQ(fragmentation.sum_of_squares.hi, 4U);
42 EXPECT_EQ(fragmentation.sum_of_squares.lo, 0U);
43 EXPECT_EQ(fragmentation.sum, 4 * kHalfWord);
44 }
45
TEST(FragmentationTest,CalculateFragmentation)46 TEST(FragmentationTest, CalculateFragmentation) {
47 // Add `n^2` fragments of size `n`, so that the sum of squares is just `n^4`.
48 // Then the root is `n^2`, the sum is `n^3`, and the result is `1 - 1/n`.
49 for (size_t n = 2; n < 20; ++n) {
50 Fragmentation fragmentation;
51 for (size_t i = 0; i < n * n; ++i) {
52 fragmentation.AddFragment(n);
53 }
54 EXPECT_FLOAT_EQ(CalculateFragmentation(fragmentation), 1.f - (1.f / n));
55 }
56 }
57
58 } // namespace
59