ProtoCore v0.0.2
Deterministic, zero-heap network stack for embedded targets
Loading...
Searching...
No Matches
wearlevel.cpp
Go to the documentation of this file.
1// Copyright (C) 2026 Douglas Quigg (dstroy0) <dquigg123@gmail.com>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4/**
5 * @file wearlevel.cpp
6 * @brief Flash wear-leveling slot selector core (see wearlevel.h).
7 */
8
10
11#if PC_ENABLE_WEARLEVEL
12
13size_t pc_wearlevel_pick(const uint32_t *counts, size_t n)
14{
15 if (!counts || n == 0)
16 {
17 return 0;
18 }
19 size_t best = 0;
20 uint32_t lowest = counts[0];
21 for (size_t i = 1; i < n; i++)
22 {
23 if (counts[i] < lowest) // strict <, so ties keep the lowest index
24 {
25 lowest = counts[i];
26 best = i;
27 }
28 }
29 return best;
30}
31
32void pc_wearlevel_mark(uint32_t *counts, size_t n, size_t idx)
33{
34 if (!counts || idx >= n)
35 {
36 return;
37 }
38 if (counts[idx] != 0xFFFFFFFFu) // saturate: never wrap a wear count back to 0
39 {
40 counts[idx]++;
41 }
42}
43
44uint32_t pc_wearlevel_spread(const uint32_t *counts, size_t n)
45{
46 if (!counts || n == 0)
47 {
48 return 0;
49 }
50 uint32_t lo = counts[0];
51 uint32_t hi = counts[0];
52 for (size_t i = 1; i < n; i++)
53 {
54 if (counts[i] < lo)
55 {
56 lo = counts[i];
57 }
58 if (counts[i] > hi)
59 {
60 hi = counts[i];
61 }
62 }
63 return hi - lo;
64}
65
66#endif // PC_ENABLE_WEARLEVEL
Flash wear-leveling slot selector (PC_ENABLE_WEARLEVEL).