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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
//
//   ________.__          __  .__  __
//  /  _____/|__| _______/  |_|__|/  |_
// /   \  ___|  |/  ___/\   __\  \   __\
// \    \_\  \  |\___ \  |  | |  ||  |
//  \______  /__/____  > |__| |__||__|
//         \/        \/
//
#![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)]
#![cfg_attr(
    test,
    allow(
        unused,
        clippy::all,
        clippy::pedantic,
        clippy::nursery,
        clippy::dbg_macro,
        clippy::unwrap_used,
        clippy::missing_docs_in_private_items,
    )
)]

pub use bytes;
pub use prost;

pub use ipc::Instruction;
pub use payload::{gistit::Inner, Gistit};

pub mod payload {
    use super::prost::Message;
    use super::Result;
    use sha2::{Digest, Sha256};

    include!(concat!(env!("OUT_DIR"), "/gistit.payload.rs"));

    pub fn hash(author: &str, description: Option<&str>, data: impl AsRef<[u8]>) -> String {
        let mut hasher = Sha256::new();
        hasher.update(data);
        hasher.update(author);
        hasher.update(description.unwrap_or(""));

        format!("{:x}", hasher.finalize())
    }

    impl Gistit {
        #[must_use]
        pub fn new(
            hash: String,
            author: String,
            description: Option<String>,
            timestamp: String,
            inner: Vec<gistit::Inner>,
        ) -> Self {
            Self {
                hash,
                author,
                description,
                timestamp,
                inner,
            }
        }

        #[must_use]
        pub const fn new_inner(
            name: String,
            lang: String,
            size: u32,
            data: String,
        ) -> gistit::Inner {
            gistit::Inner {
                name,
                lang,
                size,
                data,
            }
        }

        /// Decodes a buffer into [`Self`]
        ///
        /// # Errors
        ///
        /// Fails if buffer doesn't contain protobuf encoded data
        pub fn from_bytes(bytes: impl AsRef<[u8]>) -> Result<Self> {
            Ok(Self::decode(bytes.as_ref())?)
        }
    }
}

pub mod ipc {
    use super::Gistit;
    use super::{Error, Result};

    include!(concat!(env!("OUT_DIR"), "/gistit.ipc.rs"));

    impl Instruction {
        #[must_use]
        pub const fn request_status() -> Self {
            Self {
                kind: Some(instruction::Kind::StatusRequest(
                    instruction::StatusRequest {},
                )),
            }
        }

        #[must_use]
        pub const fn request_fetch(hash: String) -> Self {
            Self {
                kind: Some(instruction::Kind::FetchRequest(instruction::FetchRequest {
                    hash,
                })),
            }
        }

        #[must_use]
        pub const fn request_provide(gistit: Gistit) -> Self {
            Self {
                kind: Some(instruction::Kind::ProvideRequest(
                    instruction::ProvideRequest {
                        gistit: Some(gistit),
                    },
                )),
            }
        }

        #[must_use]
        pub const fn request_shutdown() -> Self {
            Self {
                kind: Some(instruction::Kind::ShutdownRequest(
                    instruction::ShutdownRequest {},
                )),
            }
        }

        #[must_use]
        pub const fn request_dial(address: String) -> Self {
            Self {
                kind: Some(instruction::Kind::DialRequest(instruction::DialRequest {
                    address,
                })),
            }
        }

        #[must_use]
        pub const fn respond_status(
            peer_id: String,
            peer_count: u32,
            pending_connections: u32,
            hosting: u32,
        ) -> Self {
            Self {
                kind: Some(instruction::Kind::StatusResponse(
                    instruction::StatusResponse {
                        peer_id,
                        peer_count,
                        pending_connections,
                        hosting,
                    },
                )),
            }
        }

        #[must_use]
        pub const fn respond_fetch(gistit: Option<Gistit>) -> Self {
            Self {
                kind: Some(instruction::Kind::FetchResponse(
                    instruction::FetchResponse { gistit },
                )),
            }
        }

        #[must_use]
        pub const fn respond_provide(maybe_hash: Option<String>) -> Self {
            Self {
                kind: Some(instruction::Kind::ProvideResponse(
                    instruction::ProvideResponse { hash: maybe_hash },
                )),
            }
        }

        /// Unwraps [`Self`] expecting a request kind
        ///
        /// # Errors
        ///
        /// Fails if instruction is not a request or is none
        #[allow(clippy::missing_const_for_fn)]
        pub fn expect_request(self) -> Result<instruction::Kind> {
            match self {
                Self {
                    kind:
                        Some(
                            instruction::Kind::FetchResponse(_)
                            | instruction::Kind::ProvideResponse(_)
                            | instruction::Kind::StatusResponse(_),
                        )
                        | None,
                } => Err(Error::Other("instruction is not a request")),
                Self {
                    kind: Some(request),
                } => Ok(request),
            }
        }

        /// Unwraps [`Self`] expecting a response kind
        ///
        /// # Errors
        ///
        /// Fails if instruction is not a response or is none
        #[allow(clippy::missing_const_for_fn)]
        pub fn expect_response(self) -> Result<instruction::Kind> {
            match self {
                Self {
                    kind:
                        Some(
                            instruction::Kind::FetchRequest(_)
                            | instruction::Kind::StatusRequest(_)
                            | instruction::Kind::ShutdownRequest(_)
                            | instruction::Kind::ProvideRequest(_),
                        )
                        | None,
                } => Err(Error::Other("instruction is not a response")),
                Self {
                    kind: Some(response),
                } => Ok(response),
            }
        }
    }
}

pub type Result<T> = std::result::Result<T, Error>;

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("decode error {0}")]
    Decode(#[from] prost::DecodeError),

    #[error("other error {0}")]
    Other(&'static str),
}

#[cfg(test)]
mod tests {
    use super::*;
    use prost::Message;

    #[test]
    fn test_payload_encode_decode() {
        let mut payload = Gistit::default();
        payload.description = Some("foo".to_owned());
        payload.author = "Matthew McCaunaghey".to_owned();

        let bytes = payload.encode_to_vec();
        assert_eq!(Gistit::decode(&*bytes).unwrap(), payload);
    }

    #[test]
    fn test_ipc_encode_decode() {
        let instruction = Instruction::request_shutdown();
        let bytes = instruction.encode_to_vec();
        assert_eq!(Instruction::decode(&*bytes).unwrap(), instruction);
    }

    #[test]
    fn test_ipc_unwrap_methods() {
        let req1 = Instruction::request_shutdown().expect_request().unwrap();
        let req2 = Instruction::request_provide(Gistit::default())
            .expect_request()
            .unwrap();
        let req3 = Instruction::request_status().expect_request().unwrap();
        let req4 = Instruction::request_fetch(String::new())
            .expect_request()
            .unwrap();

        let res1 = Instruction::respond_fetch(Some(Gistit::default()))
            .expect_response()
            .unwrap();
        let res2 = Instruction::respond_provide(None)
            .expect_response()
            .unwrap();
        let res3 = Instruction::respond_status(String::new(), 0, 0, 0)
            .expect_response()
            .unwrap();

        assert!(true);
    }
}