• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 namespace pw::allocator {
18 namespace {
19 
20 /// Adds the second number to the first, and return whether it overflowed.
AddTo(size_t & accumulate,size_t value)21 size_t AddTo(size_t& accumulate, size_t value) {
22   accumulate += value;
23   return accumulate < value ? 1 : 0;
24 }
25 
26 }  // namespace
27 
AddFragment(size_t size)28 void Fragmentation::AddFragment(size_t size) {
29   constexpr size_t kShift = sizeof(size_t) * 4;
30   constexpr size_t kMask = (size_t(1) << kShift) - 1;
31   size_t hi = size >> kShift;
32   size_t lo = size & kMask;
33   size_t crossterm = hi * lo;
34   hi = hi * hi;
35   lo = lo * lo;
36   hi += (AddTo(crossterm, crossterm)) << kShift;
37   hi += (crossterm >> kShift) + AddTo(lo, (crossterm & kMask) << kShift);
38   hi += AddTo(sum_of_squares.lo, lo);
39   sum_of_squares.hi += hi;
40   sum += size;
41 }
42 
43 }  // namespace pw::allocator
44