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
99
100
101
102
use std::str::FromStr;

use serde::{Deserialize, Serialize};

use super::utils::*;

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct PeerId(
    #[serde(
        serialize_with = "serialize_20_bytes",
        deserialize_with = "deserialize_20_bytes"
    )]
    pub [u8; 20],
);

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct InfoHash(
    #[serde(
        serialize_with = "serialize_20_bytes",
        deserialize_with = "deserialize_20_bytes"
    )]
    pub [u8; 20],
);

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AnnounceEvent {
    Started,
    Stopped,
    Completed,
    Empty,
}

impl Default for AnnounceEvent {
    fn default() -> Self {
        Self::Empty
    }
}

impl FromStr for AnnounceEvent {
    type Err = String;

    fn from_str(value: &str) -> std::result::Result<Self, String> {
        match value {
            "started" => Ok(Self::Started),
            "stopped" => Ok(Self::Stopped),
            "completed" => Ok(Self::Completed),
            "empty" => Ok(Self::Empty),
            value => Err(format!("Unknown value: {}", value)),
        }
    }
}

impl AnnounceEvent {
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Self::Started => Some("started"),
            Self::Stopped => Some("stopped"),
            Self::Completed => Some("completed"),
            Self::Empty => None,
        }
    }
}

#[cfg(test)]
impl quickcheck::Arbitrary for InfoHash {
    fn arbitrary(g: &mut quickcheck::Gen) -> Self {
        let mut arr = [b'0'; 20];

        for byte in arr.iter_mut() {
            *byte = u8::arbitrary(g);
        }

        Self(arr)
    }
}

#[cfg(test)]
impl quickcheck::Arbitrary for PeerId {
    fn arbitrary(g: &mut quickcheck::Gen) -> Self {
        let mut arr = [b'0'; 20];

        for byte in arr.iter_mut() {
            *byte = u8::arbitrary(g);
        }

        Self(arr)
    }
}

#[cfg(test)]
impl quickcheck::Arbitrary for AnnounceEvent {
    fn arbitrary(g: &mut quickcheck::Gen) -> Self {
        match (bool::arbitrary(g), bool::arbitrary(g)) {
            (false, false) => Self::Started,
            (true, false) => Self::Started,
            (false, true) => Self::Completed,
            (true, true) => Self::Empty,
        }
    }
}