Skip to content

Commit f44ea7d

Browse files
committed
x
1 parent 73665ee commit f44ea7d

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed

hoge.cc

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
// gpio_query.hpp
2+
#pragma once
3+
#include <cstddef> // size_t
4+
#include <cstdint> // uint32_t, uint8_t
5+
#include <type_traits>
6+
#include <cstdio>
7+
8+
struct gpio
9+
{
10+
int id;
11+
};
12+
13+
/* 実体(MMIO ならリンカスクリプトで配置する感じ) */
14+
struct gpio gpio0 = {0};
15+
struct gpio gpio1 = {1};
16+
17+
/*-------------------------------------------------------------------------
18+
* コントローラテーブル
19+
* 「pins[] は *累積* で末尾インデックス (exclusive-upper) を持つ」
20+
* 0〜15 : gpio0 (16本)
21+
* 16〜31 : gpio1 (16本)
22+
*------------------------------------------------------------------------*/
23+
static constexpr gpio* gpios[] = { &gpio0, &gpio1 };
24+
static constexpr uint32_t pins[] = { 16u, 32u }; // ←累積終端
25+
26+
/*=========================================================================*/
27+
/* 内部の再帰 constexpr ルックアップ */
28+
/*=========================================================================*/
29+
namespace detail
30+
{
31+
constexpr const gpio*
32+
query_gpio_recursive(std::size_t pin,
33+
const gpio* const* ctrl,
34+
const uint32_t* end,
35+
std::size_t n)
36+
{
37+
return (n == 0) ? nullptr
38+
: (pin < end[0]) ? ctrl[0] // 命中!
39+
: /* else 再帰で次のエントリへ */ query_gpio_recursive(pin,
40+
ctrl + 1,
41+
end + 1,
42+
n - 1);
43+
}
44+
}
45+
46+
/*=========================================================================*/
47+
/* 公開 API */
48+
/*=========================================================================*/
49+
/**
50+
* @brief ピン番号から GPIO コントローラを取得する(constexpr 版)。
51+
*
52+
* @param pin 論理ピン番号(0-based)。
53+
* @return 有効なら対応する gpio*。範囲外なら nullptr。
54+
*/
55+
constexpr const gpio* query_gpio(std::size_t pin) noexcept
56+
{
57+
return detail::query_gpio_recursive(pin,
58+
gpios,
59+
pins,
60+
sizeof(gpios) / sizeof(gpios[0]));
61+
}
62+
63+
/*=========================================================================*/
64+
/* 静的アサート – コンパイル時に自己診断 */
65+
/*=========================================================================*/
66+
static_assert(query_gpio( 0) == &gpio0, "pin 0 ⇒ gpio0");
67+
static_assert(query_gpio(15) == &gpio0, "pin 15 ⇒ gpio0");
68+
static_assert(query_gpio(16) == &gpio1, "pin 16 ⇒ gpio1");
69+
static_assert(query_gpio(31) == &gpio1, "pin 31 ⇒ gpio1");
70+
static_assert(query_gpio(32) == nullptr, "pin 32 は範囲外");
71+
72+
int main() {
73+
printf("%d\n", query_gpio(0)->id);
74+
printf("%d\n", query_gpio(15)->id);
75+
printf("%d\n", query_gpio(16)->id);
76+
printf("%d\n", query_gpio(31)->id);
77+
printf("%p\n", query_gpio(32));
78+
return 0;
79+
}

0 commit comments

Comments
 (0)