titan_types/
query.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
use {
    bitcoin::BlockHash,
    ordinals::{RuneId, SpacedRune},
    std::{
        fmt::{self, Display},
        str::FromStr,
    },
};

#[derive(Debug, thiserror::Error)]
pub enum BlockParseError {
    #[error("invalid block height")]
    InvalidHeight,
    #[error("invalid block hash")]
    InvalidHash,
}

#[derive(Debug)]
pub enum Block {
    Height(u64),
    Hash(BlockHash),
}

impl FromStr for Block {
    type Err = BlockParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(if s.len() == 64 {
            Self::Hash(s.parse().map_err(|_| BlockParseError::InvalidHash)?)
        } else {
            Self::Height(s.parse().map_err(|_| BlockParseError::InvalidHeight)?)
        })
    }
}

impl Display for Block {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Block::Height(height) => write!(f, "{}", height),
            Block::Hash(hash) => write!(f, "{}", hash),
        }
    }
}

impl Into<String> for Block {
    fn into(self) -> String {
        match self {
            Self::Height(height) => height.to_string(),
            Self::Hash(hash) => hash.to_string(),
        }
    }
}

#[derive(Debug, thiserror::Error)]
pub enum RuneParseError {
    #[error("invalid rune id")]
    InvalidId,
    #[error("invalid spaced rune")]
    InvalidSpacedRune,
}

#[derive(Debug)]
pub enum Rune {
    Spaced(SpacedRune),
    Id(RuneId),
}

impl FromStr for Rune {
    type Err = RuneParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.contains(':') {
            Ok(Self::Id(s.parse().map_err(|_| RuneParseError::InvalidId)?))
        } else {
            Ok(Self::Spaced(
                s.parse().map_err(|_| RuneParseError::InvalidSpacedRune)?,
            ))
        }
    }
}

impl Display for Rune {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Spaced(rune) => write!(f, "{}", rune),
            Self::Id(id) => write!(f, "{}", id),
        }
    }
}

impl Into<String> for Rune {
    fn into(self) -> String {
        match self {
            Self::Spaced(rune) => rune.to_string(),
            Self::Id(id) => id.to_string(),
        }
    }
}