Skip to main content

fire_scope/
common.rs

1use std::str::FromStr;
2use std::sync::atomic::{AtomicBool, Ordering};
3
4static DEBUG_ENABLED: AtomicBool = AtomicBool::new(false);
5
6/// デバッグの有効/無効を設定
7pub fn set_debug(enabled: bool) {
8    DEBUG_ENABLED.store(enabled, Ordering::Relaxed);
9}
10
11/// デバッグが有効かどうか
12pub fn debug_enabled() -> bool {
13    DEBUG_ENABLED.load(Ordering::Relaxed)
14}
15
16/// デバッグ出力(stderr)
17pub fn debug_log(msg: impl AsRef<str>) {
18    if debug_enabled() {
19        eprintln!("[debug] {}", msg.as_ref());
20    }
21}
22
23#[derive(Debug, Clone, Copy)]
24pub enum IpFamily {
25    V4,
26    V6,
27}
28
29impl FromStr for IpFamily {
30    type Err = &'static str;
31
32    fn from_str(s: &str) -> Result<Self, Self::Err> {
33        match s {
34            "IPv4" => Ok(IpFamily::V4),
35            "IPv6" => Ok(IpFamily::V6),
36            _ => Err("Invalid IP version. Must be 'IPv4' or 'IPv6'"),
37        }
38    }
39}
40
41impl IpFamily {
42    /// whoisのrouteキーを返す ("route:" / "route6:")
43    pub fn route_key(self) -> &'static str {
44        match self {
45            IpFamily::V4 => "route:",
46            IpFamily::V6 => "route6:",
47        }
48    }
49
50    /// ログやファイル名で使うラベル用
51    pub fn as_str(self) -> &'static str {
52        match self {
53            IpFamily::V4 => "IPv4",
54            IpFamily::V6 => "IPv6",
55        }
56    }
57}
58
59/// 出力形式を管理するためのenum
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub enum OutputFormat {
62    Txt,
63    Nft,
64}
65
66// ここで標準トレイト `FromStr` を実装し、文字列 => `OutputFormat` 変換を行う
67impl FromStr for OutputFormat {
68    type Err = &'static str;
69
70    fn from_str(s: &str) -> Result<Self, Self::Err> {
71        match s.to_lowercase().as_str() {
72            "nft" => Ok(OutputFormat::Nft),
73            "txt" | "" => Ok(OutputFormat::Txt),
74            _ => Err("Invalid output format. Valid options: 'txt' or 'nft'"),
75        }
76    }
77}