Add sorted_list, timer_queue, and DHCP discover with inline options

This commit is contained in:
Ian Gulliver
2026-04-05 21:23:14 +09:00
parent 421cb5840e
commit 28caa2e590
6 changed files with 175 additions and 0 deletions

5
include/dhcp.h Normal file
View File

@@ -0,0 +1,5 @@
#pragma once
#include <array>
#include "timer_queue.h"
void dhcp_start(timer_queue& timers, const std::array<uint8_t, 6>& mac);

58
include/sorted_list.h Normal file
View File

@@ -0,0 +1,58 @@
#pragma once
#include <cstdint>
#include <new>
#include <utility>
template <typename T, int N>
struct sorted_list {
struct node {
alignas(T) uint8_t storage[sizeof(T)];
node* next = nullptr;
T& value() { return *reinterpret_cast<T*>(storage); }
const T& value() const { return *reinterpret_cast<const T*>(storage); }
};
node nodes[N];
node* head = nullptr;
node* free_head = &nodes[0];
sorted_list() {
for (int i = 0; i < N - 1; i++) nodes[i].next = &nodes[i + 1];
nodes[N - 1].next = nullptr;
}
bool empty() const { return head == nullptr; }
bool full() const { return free_head == nullptr; }
T& front() { return head->value(); }
const T& front() const { return head->value(); }
void insert(T value) {
if (full()) return;
node* n = free_head;
free_head = n->next;
new (n->storage) T(std::move(value));
if (!head || n->value() < head->value()) {
n->next = head;
head = n;
return;
}
node* cur = head;
while (cur->next && !(n->value() < cur->next->value()))
cur = cur->next;
n->next = cur->next;
cur->next = n;
}
void pop_front() {
if (empty()) return;
node* n = head;
head = n->next;
n->value().~T();
n->next = free_head;
free_head = n;
}
};

50
include/timer_queue.h Normal file
View File

@@ -0,0 +1,50 @@
#pragma once
#include <functional>
#include "pico/time.h"
#include "sorted_list.h"
struct timer_entry {
absolute_time_t when;
std::function<void()> fn;
};
inline bool operator<(const timer_entry& a, const timer_entry& b) {
return absolute_time_diff_us(b.when, a.when) < 0;
}
struct timer_queue {
sorted_list<timer_entry, 16> queue;
alarm_id_t alarm = -1;
void schedule(absolute_time_t when, std::function<void()> fn) {
queue.insert({when, std::move(fn)});
arm();
}
void schedule_ms(uint32_t ms, std::function<void()> fn) {
schedule(make_timeout_time_ms(ms), std::move(fn));
}
void run() {
while (!queue.empty()) {
auto& front = queue.front();
if (absolute_time_diff_us(get_absolute_time(), front.when) > 0) break;
auto fn = std::move(front.fn);
queue.pop_front();
fn();
}
arm();
}
bool empty() const { return queue.empty(); }
private:
static int64_t alarm_cb(alarm_id_t, void*) { return 0; }
void arm() {
if (alarm >= 0) cancel_alarm(alarm);
alarm = -1;
if (!queue.empty())
alarm = add_alarm_at(queue.front().when, alarm_cb, nullptr, false);
}
};